Skip to content

Commit b33f99b

Browse files
authored
Create count-substrings-that-differ-by-one-character.cpp
1 parent e9ee13f commit b33f99b

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// Time: O(m * n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
int countSubstrings(string s, string t) {
7+
int result = 0;
8+
// for each possible alignment, count the number of substrs that differ by 1 char
9+
for (int i = 0; i < size(s); ++i) {
10+
result += count(s, t, i, 0);
11+
}
12+
for (int j = 1; j < size(t); ++j) { // j starts from 1 to avoid duplicated count(0, 0)
13+
result += count(s, t, 0, j);
14+
}
15+
return result;
16+
}
17+
18+
private:
19+
int count(const string& s, const string& t, int i, int j) {
20+
int l = min(size(s) - i, size(t) - j);
21+
int result = 0, left_cnt = 0, right_cnt = 0; // left and right consecutive same counts relative to the different char
22+
for (int k = 0; k < l; ++k) {
23+
++right_cnt;
24+
if (s[i + k] != t[j + k]) {
25+
left_cnt = right_cnt;
26+
right_cnt = 0;
27+
// left_i = i+k-left+1
28+
}
29+
result += left_cnt; // target substrs are [s[left_i+c:i+k+1] for c in xrange(left_cnt)]
30+
}
31+
return result;
32+
}
33+
};

0 commit comments

Comments
 (0)