当前位置: 代码迷 >> 综合 >> 算法提高 Substrings(string 用法)
  详细解决方案

算法提高 Substrings(string 用法)

热度:70   发布时间:2023-12-10 07:46:44.0

资源限制
时间限制:1.0s 内存限制:256.0MB
问题描述
  You are given a number of case-sensitive strings of alphabetic characters, find the largest string X, such that either X, or its inverse can be found as a substring of any of the given strings.
输入格式
  The first line of the input contains a single integer t (1 <= t <= 10), the number of test cases, followed by the input data for each test case. The first line of each test case contains a single integer n (1 <= n <= 100), the number of given strings, followed by n lines, each representing one string of minimum length 1 and maximum length 100. There is no extra white space before and after a string.
输出格式
  There should be one line per test case containing the length of the largest string found.
样例输入
2
3
ABCD
BCDFF
BRCD
2
rose
orchid
样例输出
2
2
试题来源
  Tehran 2002 Preliminary


题解

中文题意:给你1-100个字符串,你要从中找一个最长的子串,该子串或者其逆序必须是所有字符串的子串。
??首先获得最短的那个字符串,然后生成子串,之后遍历每一个其他串求解,主要使用 string.find()函数,子串的逆序可以使用 reverse( iterator_first,iterator_last)。

#include<iostream>
#include<string>
#include<algorithm>using namespace std;string s[100];
int n, k;bool judge(string sub, int c) {
    string rev_sub = sub;	//记录反串reverse(rev_sub.begin(), rev_sub.end());for (int i = 0; i < k; i++) {
    if (i == c)continue;if (s[i].find(sub) == s[i].npos && s[i].find(rev_sub) == s[i].npos)return false;}return true;
}int main() {
    int c;      //记录最短的那个stringstring sub;  //生成的子串int ans = 0;cin >> n;while (n--) {
    c = 0;cin >> k;for (int i = 0; i < k; i++) {
    cin >> s[i];if (s[i].length() < s[c].length())c = i;		//记录最短的那一个string}//生成子串for (int i = 0; i < s[c].length(); i++)for (int j = i; j < s[c].length(); j++) {
    sub = s[c].substr(i, j + 1);	//获得子串if (judge(sub, c))      //判断其他串是否有该子串ans = max(ans, j-i+1);}cout << ans << endl;}return 0;
}
  相关解决方案