题目
题目链接
解题思路
- 题目要求计算字符串
T
T
T 与
S
S
S 中所有长度为
∣
T
∣
|T|
∣T∣ 的子串的距离和
- 字符串距离定义:对应位置字符不同的数量
- 解题策略:
- 使用滑动窗口统计当前窗口中’a’和’b’的数量
- 对于
S
S
S 中的每个字符,根据它与
T
T
T 中对应位置字符的不同来累加距离
- 当窗口移动时,更新字符计数
代码
#include <iostream>
#include <string>
using namespace std;
int main() {
string s, t;
cin >> s >> t;
long long lens = s.length();
long long lent = t.length();
long long count_a = 0, count_b = 0, total = 0;
int pos = 0;
for(int i = 0; i < lens; i++) {
if(i < lent) {
if(t[i] == 'a') count_a++;
else count_b++;
}
if(s[i] == 'a') {
total += count_b;
} else {
total += count_a;
}
if(i >= lens - lent) {
if(t[pos++] == 'a') count_a--;
else count_b--;
}
}
cout << total << endl;
return 0;
}
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.next();
String t = sc.next();
long lens = s.length();
long lent = t.length();
long countA = 0, countB = 0, total = 0;
int pos = 0;
for(int i = 0; i < lens; i++) {
if(i < lent) {
if(t.charAt(i) == 'a') countA++;
else countB++;
}
if(s.charAt(i) == 'a') {
total += countB;
} else {
total += countA;
}
if(i >= lens - lent) {
if(t.charAt(pos++) == 'a') countA--;
else countB--;
}
}
System.out.println(total);
}
}
s = input()
t = input()
lens = len(s)
lent = len(t)
count_a = count_b = total = pos = 0
for i in range(lens):
if i < lent:
if t[i] == 'a':
count_a += 1
else:
count_b += 1
if s[i] == 'a':
total += count_b
else:
total += count_a
if i >= lens - lent:
if t[pos] == 'a':
count_a -= 1
else:
count_b -= 1
pos += 1
print(total)
算法及复杂度
- 算法:滑动窗口
- 时间复杂度:
O
(
∣
S
∣
)
\mathcal{O}(|S|)
O(∣S∣) - 只需要遍历一次字符串S
- 空间复杂度:
O
(
1
)
\mathcal{O}(1)
O(1) - 只需要常数级别的额外空间