Substrings(hdu1238)字串匹配

來源:互聯網
上載者:User

標籤:des   style   blog   http   color   java   os   io   

Substrings

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 7205 Accepted Submission(s): 3255


Problem DescriptionYou 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. 

 

InputThe first line of the input file 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.  

 

OutputThere should be one line per test case containing the length of the largest string found. 

 

Sample Input23ABCDBCDFFBRCD2roseorchid 

 

Sample Output22  

這個找字串的問題,題目大概意思就是找出所有字串中共同擁有的一個子串,

該子串(正、逆字元)是任何一個母串的子串,求該子串的最長長度。

想到用STRING裡的成員函數和STL的reverse反轉函數,

思路:

先找出最短的母串,即該符合要求的子串肯定在這個母串中,即在從長到短

從最短母串中取子串,在子串正反去查看是否符合要求。

說實話今天又學到了一些知識,我表示這C++的很多函數真shi 強大啊。

 

 

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

 

 

 

#include<iostream>#include<string>#include<algorithm>//STL reverse函數的標頭檔,reverse反轉函數,using namespace std;int main(){    int cas,len,sub,maxn;    int n,k,i,j;    string s[102];    cin>>cas;    while(cas--)    {        cin>>n;        len=1000;        sub=0;        for(i=0; i<n; i++)        {            cin>>s[i];            if(len>s[i].size())//找最小 的母串            {                len=s[i].size();                sub=i;            }        }        maxn=0;        for(i=s[sub].size(); i>0; i--) //從最小的母串開始從長到短找子串,        {            for(j=0; j<s[sub].size()-i+1; j++) //長度為i的子串在母串中找            {                string s1,s2;//s1為子串正 ,s2為子串反                s1=s[sub].substr(j,i);//去j開始i長度是字元                s2=s1;                reverse(s2.begin(),s2.end());//反串                for( k=0; k<n; k++)                {                    if(s[k].find(s1,0)==-1&&s[k].find(s2,0)==-1) //當正反子串在母串中都未發現時即跳出                        break;                }                if(k==n&&maxn<s1.size())                    maxn=s1.size();            }        }        cout<<maxn<<endl;    }    return 0;}

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.