字符串中连续最多的子串

把字符串用后缀树的形式表现出来如下:

a b c a b c a b c d e .substr[0]

b c a b c a b c d e ....substr[1]

c a b c a b c d e .......substr[2]

a b c a b c d e ..........substr[3]

b c a b c d e .............substr[4]

c a b c d e ...............substr[5]

a b c d e .................substr[6]

b c d e ...................substr[7]

c d e .....................substr[8]

d e ........................substr[9]

e ..........................substr[10]

可以观察到,若存在连续出现的字串,则满足 substr[0].substr(i,j-i) == substr[j].substr(0,j-i),例如上例中的

substr[0].substr(0,3-0) == substr[3].substr(0,3-0)

我们换一种方式来看,不需要生成后缀组,但思想还是一样的。

代码:

代码中str.substr(pos2,offset)其实相当于后缀组的substr[pos2].substr(0,offset)

把字符串写成后缀组其实相当于站在不同的位置往后看这个数组,所以其实并不需要额外增加存储空间来生成后缀组。

 

程序:

 

pair<int, string>fun(const string &str)
{
  vector<string> substrs;
  int maxcount = 1;
  nt count = 1;
  string substr;
  int i;
  int len = str.length();
  for (i = 0; i < len; i++)
     substrs.push_back(str.substr(i, len));//产生后缀子串
  for (i = 0; i < len; i++)
  {
    for (int j = i + 1; j < len; j++)
    {
    count = 1;
    if (substrs[i].substr(0, j - i) == substrs[j].substr(0, j - i))//offet 为j-i
    {
    count++;
    for (int k = j + j - i; k < len; k++)//以offet为单位,进行查找,不连续就退出
    {
    if (substrs[i].substr(0, j - i) == substrs[k].substr(0, j - i))
    count++;
    else//不连续就退出
      break;
    }
    if (count > maxcount)
    {
    maxcount = count;
    substr = substrs[i].substr(0, j - i);
    }
     }
 }

 }
  return make_pair(maxcount, substr);
}
int main()
{
     string str="abcabcabccc";
      pair<int, string> res;
     res = fun(str);
       cout << res.first << " " << res.second;
      cin.get();
     return 0;
}

转载于:https://www.cnblogs.com/ranranblog/p/5616619.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值