1. 程式人生 > >求一個字符串中出現同樣且長度最長的字符串

求一個字符串中出現同樣且長度最長的字符串

data 技術 alt fin sso 從大到小 popu jsb tex

技術分享題目:輸入一行字符串。找出當中出現的同樣且長度最長的字符串,輸出它及其首字符的位置。

比如:“yyabcdabjcabceg",輸出結果應該為abc 和3.

技術分享

#include<iostream>
#include<string>
using namespace std;
int main()
{
string str, tep;
cout << "輸入字符串" << endl;
cin >> str;
for (int i = str.length() - 1; i > 1; i--)

{
for (int j = 0; j < str.length(); j++)
{
if (j + i <= str.length())
{
size_t t = 0;
size_t num = 0;
tep = str.substr(j, i);//從大到小取子串
t = str.find(tep);//正序查找
num = str.rfind(tep);//逆序查找
if (t != num)//假設兩次查找位置不一致,說明存在反復子串
{
cout << tep << " " << t + 1 << endl;//輸出子串及位置
system("pause");
return 0;


}
}
}
}
}

求一個字符串中出現同樣且長度最長的字符串