题目:给一个字符串、例如 “ababc”要求返回“ab”. 因为“ab”连续重复出现且最长。 用C/C++语言写一函数完成该算法,给出复杂度
如果有多个答案就返回第一个了
像:ababcdcd, 输出是就是ab了
复杂度分析:
i = 1
for (i to N)
{
for (0 to N-i)
{
k = i
for (0 to i) /* 字符串copy */
}
}
O(N^3)
有错请指出哈...
代码
#include
<
iostream
>
#include < string >
#include < map >
#include < algorithm >
using namespace std;
int main()
{
string str, tmp, buf;
int i, j, k, index, len, max;
map < string , int > my_map;
cout << " Enter a string: " << endl;
cin >> str;
len = str.size();
for (k = 1 ; k <= len; k ++ ) /* 长度为K的字符串 */
{
cout << " 串长为 " << k << " : " << endl;
for (i = 0 ; i < len - k + 1 ; i ++ ) /* 串长为K的字符串的开头 */
{
index = k;
tmp = "" ;
j = i;
while (index -- ) /* 串长为j的 */
{
tmp += str[j ++ ];
}
my_map[tmp] ++ ; /* 收集 */
cout << tmp << " " ;
}
cout << endl;
}
len = str.size();
max = - 1 ;
buf = "" ;
for (k = 1 ; k <= len; k ++ ) /* 长度为K的字符串 */
{
for (i = 0 ; i < len - k + 1 ; i ++ ) /* 串长为K的字符串的开头 */
{
index = k;
tmp = "" ;
j = i;
while (index -- ) /* 串长为j的 */
{
tmp += str[j ++ ];
}
if ((max == - 1 && my_map[tmp] > 1 ) /* mY_map[tmp] >1:连续重复 */
|| (my_map[tmp] > 1 && max < tmp.size())) /* max < ~.size()且最长 */
{
buf = tmp;
max = tmp.size();
}
}
}
cout << endl << " 应该返回的串是:\n " << buf << endl;
system( " pause " );
}
#include < string >
#include < map >
#include < algorithm >
using namespace std;
int main()
{
string str, tmp, buf;
int i, j, k, index, len, max;
map < string , int > my_map;
cout << " Enter a string: " << endl;
cin >> str;
len = str.size();
for (k = 1 ; k <= len; k ++ ) /* 长度为K的字符串 */
{
cout << " 串长为 " << k << " : " << endl;
for (i = 0 ; i < len - k + 1 ; i ++ ) /* 串长为K的字符串的开头 */
{
index = k;
tmp = "" ;
j = i;
while (index -- ) /* 串长为j的 */
{
tmp += str[j ++ ];
}
my_map[tmp] ++ ; /* 收集 */
cout << tmp << " " ;
}
cout << endl;
}
len = str.size();
max = - 1 ;
buf = "" ;
for (k = 1 ; k <= len; k ++ ) /* 长度为K的字符串 */
{
for (i = 0 ; i < len - k + 1 ; i ++ ) /* 串长为K的字符串的开头 */
{
index = k;
tmp = "" ;
j = i;
while (index -- ) /* 串长为j的 */
{
tmp += str[j ++ ];
}
if ((max == - 1 && my_map[tmp] > 1 ) /* mY_map[tmp] >1:连续重复 */
|| (my_map[tmp] > 1 && max < tmp.size())) /* max < ~.size()且最长 */
{
buf = tmp;
max = tmp.size();
}
}
}
cout << endl << " 应该返回的串是:\n " << buf << endl;
system( " pause " );
}