题目
题目链接
解题思路
简化版滑动窗口:
- 只考虑 \(A\) 串与 \(B\) 串的对齐部分
- 统计对齐部分的不同字符数
- 取所有可能位置中的最小值
关键点
- 使用字符数组提高效率
- 只统计对齐部分的差异
- 使用BufferedReader提高输入效率
代码
#include <bits/stdc++.h>
using namespace std;class Solution {
public:int minDifference(string& A, string& B) {int lenA = A.length();int lenB = B.length();int n = lenB - lenA;int result = INT_MAX;// 遍历所有可能的对齐位置for (int i = 0; i <= n; i++) {int count = 0;// 只比较对齐部分for (int j = 0; j < lenA; j++) {if (A[j] != B[j + i]) {count++;}}result = min(result, count);}return result;}
};int main() {ios::sync_with_stdio(false);cin.tie(nullptr);string A, B;getline(cin, A);getline(cin, B);Solution sol;cout << sol.minDifference(A, B) << endl;return 0;
}
import java.io.*;public class Main {static class Solution {public int minDifference(char[] A, char[] B) {int n = B.length - A.length;int result = Integer.MAX_VALUE;// 遍历所有可能的对齐位置for (int i = 0; i <= n; i++) {int count = 0;// 只比较对齐部分for (int j = 0; j < A.length; j++) {if (A[j] != B[j + i]) {count++;}}result = Math.min(result, count);}return result;}}public static void main(String[] args) throws IOException {BufferedReader br = new BufferedReader(new InputStreamReader(System.in));char[] A = br.readLine().toCharArray();char[] B = br.readLine().toCharArray();Solution sol = new Solution();System.out.println(sol.minDifference(A, B));}
}
class Solution:def min_difference(self, A: str, B: str) -> int:n = len(B) - len(A)result = float('inf')# 遍历所有可能的对齐位置for i in range(n + 1):count = 0# 只比较对齐部分for j in range(len(A)):if A[j] != B[j + i]:count += 1result = min(result, count)return resultdef main():A = input().strip()B = input().strip()sol = Solution()print(sol.min_difference(A, B))if __name__ == "__main__":main()
算法及复杂度
- 算法:简化版滑动窗口
- 时间复杂度:\(\mathcal{O}(n * m)\),\(n\) 为 \(B-A\) 的长度差,\(m\) 为 \(A\) 的长度
- 空间复杂度:\(\mathcal{O}(1)\),不考虑输入存储