hdu-1238 Substrings

http://acm.hdu.edu.cn/showproblem.php?pid=1238

还是一直钟情于string,虽然有很多bug,但和char[]比起来还是忍了^^

#include <iostream>
#include <string>
using namespace std;

string rever(string str)
{
    int len = str.size(), i, j;
    for (i = 0, j = len - 1; i < j; ++i, --j)
    {
        char tmp = str[i];
        str[i] = str[j];
        str[j] = tmp;
    }
    return  str;
}

//这个函数是参考别人char[]的做法的

bool ok(string &strSource, string &strDense)
{
    int len1 = strSource.size(), len2 = strDense.size(), i, j;
    bool flag = true;
    for (i = 0; i < len1 - len2 + 1; ++i)
    {
        flag = true;
        int k = i;
        for (j = 0; j < len2; ++j, ++k)
        {
            if (strDense[j] != strSource[k])
            {
                flag = false;
                break;
            }
        }
        if (flag)
            return true;
    }
    return false;
}

int main()
{
    int nCases, n, i, j, k;
    string str[101], str1, str2;
    bool flag;

    scanf("%d", &nCases);
    while (nCases--)
    {
        int nMin = 150;
        scanf("%d", &n);
        for (i = 0; i < n; ++i)
        {
            cin >> str[i];
            if (str[i].size() < nMin)
            {
                nMin = str[i].size();
                k = i;
            }
        }
        if(n==0)
        {
            cout<<0<<endl;
            continue;
        }
        else if(n==1)
        {
            cout<<str[0].size()<<endl;
            continue;
        }
        swap(str[k], str[0]);
        nMin = str[0].size();

        int len = 0;
        for (i = 0; i < nMin; ++i)
        {
            for (j = i + 1; j <= nMin; ++j)
            {
                flag = false;
                str1 = str[0].substr(i, j - i);
                str2 = rever(str1);
                for (k = 1; k < n; ++k)
                {
                    if (ok(str[k], str1) || ok(str[k], str2))
                    {
                        flag = true;
                    }
                    else
                    {
                        flag = false;
                        break;
                    }
                }
                if (len < str1.length() && flag)
                    len = str1.length();
            }
        }
        cout << len << endl;
    }

    return 0;
}

你可能感兴趣的:(hdu-1238 Substrings)