高效处理二进制字符串中的前缀查询
给定一个二进制字符串 S
(仅包含“0”或“1”),我们需要处理以下 2 种类型的查询:
1 K V
:更新 < 的值code>Kth 字符串中值为V
的索引(只能是 0/1 个字符)。2 L R
:打印Fun(L, R)
的值:对于子字符串X = S[L: R]
,我们采用前缀Y = S[0: R - L]
并计算X[i] != Y[j]
的位置数量,其中 i = [L, R ],j = [0,R - L]。
约束:
N (length of S) <= 10 ^ 5
Q (number of query ) <= 10 ^ 5
示例测试用例:
S = "111101"
Query(2 3 5) = 1
说明:
此处,X = '101' 且 Y = '111',仅 X[1 ] != Y[1]
,其余所有位位置相同。
方法:
public List<Integer> solve(StringBuffer S, int[][] q) {
int N = S.length();
int Q = q.length();
List<Integer> result = new ArrayList<>();
for(int i = 0; i < Q; i++) {
if(Q[i][0] == 1) // type-1
S.setCharAt(Q[i][1], Q[i][2]);
else if(Q[i][0] == 2) { // type-2
int L = Q[i][1];
int R = Q[i][2];
int count = 0;
for(int i = 0; i < R - L + 1; i++, L++) {
if(S.charAt(i) != S.charAt(L))
count += 1;
}
result.add(count);
}
}
return result;
}
时间复杂度:O(Q * N)
我们怎样才能更有效地解决这个问题,使得每个查询的时间复杂度小于O(N)
。
Given an binary string S
(contains '0' or '1' only), we need to process 2 type of queries as following:
1 K V
: Update the value ofKth
index in the string with valueV
(can only be 0/1 character).2 L R
: Print the value ofFun(L, R)
: for substringX = S[L: R]
and we take the prefixY = S[0: R - L]
and count the num of positions for whichX[i] != Y[j]
, for i = [L, R], j = [0, R - L].
Constraints :
N (length of S) <= 10 ^ 5
Q (number of query ) <= 10 ^ 5
Sample test case:
S = "111101"
Query(2 3 5) = 1
Explanation :
Here, X = '101' and Y = '111', only X[1] != Y[1]
, rest all bits are positionally same.
Approach:
public List<Integer> solve(StringBuffer S, int[][] q) {
int N = S.length();
int Q = q.length();
List<Integer> result = new ArrayList<>();
for(int i = 0; i < Q; i++) {
if(Q[i][0] == 1) // type-1
S.setCharAt(Q[i][1], Q[i][2]);
else if(Q[i][0] == 2) { // type-2
int L = Q[i][1];
int R = Q[i][2];
int count = 0;
for(int i = 0; i < R - L + 1; i++, L++) {
if(S.charAt(i) != S.charAt(L))
count += 1;
}
result.add(count);
}
}
return result;
}
Time Complexity : O(Q * N)
How can we solve this problem more efficiently, such that the time complexity for each query would be less that O(N)
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论