算法提高 Substrings(string 用法)

资源限制
时间限制: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;      //记录最短的那个string
    string 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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值