1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class Solution { public int[] platesBetweenCandles(String s, int[][] queries) { int n = s.length(), m = queries.length; int[] ans = new int[m], sum = new int[n + 1], left = new int[n], right = new int[n]; for (int i = 0, j = n - 1, p = -1, q = -1; i < n; ++i, --j) { if (s.charAt(i) == '|') p = i; if (s.charAt(j) == '|') q = j; left[i] = p; right[j] = q; sum[i + 1] = sum[i] + (s.charAt(i) == '*' ? 1 : 0); } for (int i = 0; i < m; ++i) { int a = queries[i][0], b = queries[i][1]; int x = right[a], y = left[b]; if (x != -1 && x <= y) ans[i] = sum[y + 1] - sum[x]; } return ans; } }
|