题解 | #字符串距离#
字符串距离
https://www.nowcoder.com/practice/c0ccc2e437f0473e8e5ebb7703c24089
解题思路
- 题目要求计算字符串
与
中所有长度为
的子串的距离和
- 字符串距离定义:对应位置字符不同的数量
- 解题策略:
- 使用滑动窗口统计当前窗口中'a'和'b'的数量
- 对于
中的每个字符,根据它与
中对应位置字符的不同来累加距离
- 当窗口移动时,更新字符计数
代码
#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;
// 遍历字符串S
for(int i = 0; i < lens; i++) {
// 统计T中字符数量
if(i < lent) {
if(t[i] == 'a') count_a++;
else count_b++;
}
// 计算距离
if(s[i] == 'a') {
total += count_b; // 与'b'不同
} else {
total += count_a; // 与'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;
// 遍历字符串S
for(int i = 0; i < lens; i++) {
// 统计T中字符数量
if(i < lent) {
if(t.charAt(i) == 'a') countA++;
else countB++;
}
// 计算距离
if(s.charAt(i) == 'a') {
total += countB; // 与'b'不同
} else {
total += countA; // 与'a'不同
}
// 更新滑动窗口
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
# 遍历字符串S
for i in range(lens):
# 统计T中字符数量
if i < lent:
if t[i] == 'a':
count_a += 1
else:
count_b += 1
# 计算距离
if s[i] == 'a':
total += count_b # 与'b'不同
else:
total += count_a # 与'a'不同
# 更新滑动窗口
if i >= lens - lent:
if t[pos] == 'a':
count_a -= 1
else:
count_b -= 1
pos += 1
print(total)
算法及复杂度
- 算法:滑动窗口
- 时间复杂度:
- 只需要遍历一次字符串S
- 空间复杂度:
- 只需要常数级别的额外空间