HDU - 6485 Similar Strings(尺取法)

题目描述:给两个字符串 A 和 B,要求求出长度都为 S 的子串 A’ 和 B’ 中最多有 K 个位置不同的最长长度 S 。
例如:
当 K 为 2 时,字符串 A “abcdefg” 和 字符串 B “pbedojg”
因为子串 A’ “abcd” 和 子串 B’ “pbed” 有两个位置不同,长度为 4,为最长长度。所以答案为 4。

#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
int ans, k;
const int maxn = 4050;
char s1[maxn], s2[maxn];
void cq(char s11[], char s22[]) {
    
    
	//让长度为两者长度较小值 
	int len = min(strlen(s11), strlen(s22));
	int cnt = 0;
	// left为子串左端点,right为子串右端点 
	int right = 0;
	for(int left=0; left<len; left++) {
    
    
		while(right < len) {
    
     
			//如果该位置不同 
			if(s11[right] != s22[right]) {
    
    
				//如果不同的数目超过 K,就结束循环 
				if(cnt+1>k)
					break;
				cnt++;
			}
			right++;  //继续往后检查 
		}
		ans = max(ans, right-left);
		if(s11[left] != s22[left])
		//因为要将左端点右移
		//所以如果两个子串的左端点不相等
		//需要将不相同的数目 -1 
			cnt--;
	}
}
int main(void) {
    
    
	int T;
	scanf("%d", &T);
	while(T--) {
    
    
		ans = 0;
		scanf("%d", &k);
		scanf("%s %s", s1, s2);
		int len1 = strlen(s1);
		int len2 = strlen(s2);
		//将两个字符串的所有字串进行检查 
		for(int i=0; i<len1; i++)
			cq(s1+i, s2);
		for(int i=0; i<len2; i++)
			cq(s2+i, s1);
		printf("%d\n", ans);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_51250927/article/details/113774850