Skip to content

Commit f46fc65

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

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# Time: O(m * n)
2+
# Space: O(1)
3+
4+
class Solution(object):
5+
def countSubstrings(self, s, t):
6+
"""
7+
:type s: str
8+
:type t: str
9+
:rtype: int
10+
"""
11+
def count(i, j): # for each possible alignment, count the number of substrs that differ by 1 char
12+
result = left_cnt = right_cnt = 0 # left and right consecutive same counts relative to the different char
13+
for k in xrange(min(len(s)-i, len(t)-j)):
14+
right_cnt += 1
15+
if s[i+k] != t[j+k]:
16+
left_cnt, right_cnt = right_cnt, 0
17+
# prev_i = i+k-prev+1
18+
result += left_cnt # target substrs are [s[left_i+c:i+k+1] for c in xrange(left_cnt)]
19+
return result
20+
21+
return sum(count(i, 0) for i in xrange(len(s))) + \
22+
sum(count(0, j) for j in xrange(1, len(t)))

0 commit comments

Comments
 (0)