Correcting Mistakes
Analyzing the mistakes people make while typing search queries is a complex and an interesting work. As there is no guaranteed way to determine what the user originally meant by typing some query, we have to use different sorts of heuristics.
Polycarp needed to write a code that could, given two words, check whether they could have been obtained from the same word as a result of typos. Polycarpus suggested that the most common typo is skipping exactly one letter as you type a word.
Implement a program that can, given two distinct words S S S and T T T of the same length n n n determine how many words W W W of length n + 1 n + 1 n + 1 are there with such property that you can transform W W W into both S S S, and T T T by deleting exactly one character. Words S S S and T T T consist of lowercase English letters. Word W W W also should consist of lowercase English letters.
Input
The first line contains integer n n n ( 1 ≤ n ≤ 100 000 1 \leq n \leq 100 000 1≤n ≤ 100 000) — the length of words S S S and T T T.
The second line contains word S S S.
The third line contains word T T T.
Words S S S and T T T consist of lowercase English letters. It is guaranteed that S S S and T T T are distinct words.
Output
Print a single integer — the number of distinct words W W W that can be transformed to S S S and T T T due to a typo.
Example
i n p u t \tt input input |
---|
7 reading trading |
o u t p u t \tt output output |
1 |
i n p u t \tt input input |
---|
5 sweet sheep |
o u t p u t \tt output output |
0 |
i n p u t \tt input input |
---|
3 toy try |
o u t p u t \tt output output |
2 |
Note
In the first sample test the two given words could be obtained only from word “treading” (the deleted letters are marked in bold).
In the second sample test the two given words couldn’t be obtained from the same word by removing one letter.
In the third sample test the two given words could be obtained from either word “tory” or word “troy”.
Tutorial
先将两个字符串 S S S 和 T T T 分别从前往后遍历一次和从后往前遍历一次,找到第一个和最后一个字母不同的位置,取中间的串作比较,如果一个子串的头不等于另一个子串的尾,则答案加一,所以答案区间为 [ 0 , 2 ] [0, 2] [0,2]
此解法时间复杂度为 O ( n ) \mathcal O(n) O(n)
Solution
n = int(input())
s, t, l, r = input(), input(), -1, -1
for i in range(n):
if s[i] != t[i]:
if l == -1:
l = i
r = i
print((s[l : r] == t[l + 1 : r + 1]) + (t[l : r] == s[l + 1 : r + 1]))