题目链接hdu2572

解题思路:水题…但是WA了好几发,一直想在原串中剪切,然后得到符合的串。不过要考虑的case很多。数据规模小,完全可以暴力枚举所有字串,然后匹配。


AC代码

#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <string>
#include <deque>
#include <queue>
#include <set>
#include <map>
#include <stack>
#include <vector>
#include <utility>

using namespace std;

int main() {
	ios::sync_with_stdio(false);
	
	int T;
	string _union,str1,str2;
	
	cin >> T;
	while (T--) {
		cin >> _union >> str1 >> str2;
		
		int f1 = _union.find(str1);
		int f2 = _union.find(str2);
		
		if(f1 == string::npos || f2 == string::npos){
			cout << "No" << '\n';
			continue;
		}else	if(str1.find(str2) != string::npos) {
			cout << str1 << '\n';
			continue;
		}else if(str2.find(str1) != string::npos) {
			cout << str2 << '\n';
			continue;
		}
		
		string tmp,ans(_union);
		for (string::iterator it1 = _union.begin(); it1 != _union.end(); it1++) {
			for (string::iterator it2 = _union.begin(); it2 <= it1; it2++) {
				tmp = _union.substr(it2 - _union.begin(),it1 - it2 + 1);
// cout << "tmp = " << tmp << endl;
				if(tmp.find(str1) != string::npos && tmp.find(str2) != string::npos) {
					if(ans.size() > tmp.size() || ans.size() == tmp.size() && ans > tmp) {
						ans = tmp;
					}
				}
			}
		}
		cout << ans << '\n';
	}
	return 0;
}

BUG代码

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main() {
    int T, index_start, len, flag;
    char pub[1100], str1[200], str2[200], tmp[1100];
    scanf ("%d", &T);
    getchar();
    while (T--) {
        gets (pub);
        gets (str1);
        gets (str2);
        len = strlen(pub);
        index_start = 0;
        flag = 1;
        for (int i = strlen(str1); i <= len && flag; i++) {
            for (int j = 0; j <= len-i && flag; j++) {
                strncpy (tmp, pub + j, i);
                if(strstr(tmp, str1) && strstr(tmp, str2)) {
                    index_start = j;
                    len = i;
                    flag = 0;
                }
            }
        }

        if(flag) {
            puts("No");
        }else {
            pub[index_start + len] = 0;
            puts(pub+index_start);
        }
    }
    return 0;
}