码迷,mamicode.com
首页 > 其他好文 > 详细

字符串中最长的不重合字串长度

时间:2014-07-05 17:03:55      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   strong   os   for   

例子

"abmadsefadd"  最长长度为5

"avoaid"           最长长度为3

 

思路

空间换时间hashTable,标准下其实位置beg。初始化全局最大值0。开辟字符数组,起初标为0。

访问数组时

  • 如果该字符在hashTable对应的哈希值为1,则计算当前位置到beg的距离,并且把beg赋值为当前位置。如果大于全局最大值,则替换全局最大值
  • 如果该字符在hashTable对应的哈希值为0,则置1

 

参考代码

#include <iostream>
using namespace std;

int getMaxLen(const string &s)
{
    int beg = 0;
    int span = 0;
    int maxspan = 0;
    int hashTable[128];
    for (int i = 0; i < 128; ++i)
        hashTable[i] = 0;
    for(int i = 0; i < s.size(); ++i)
    {
        if (hashTable[s[i]] == 1)
        {
            span = i - beg;
            beg = i;
            hashTable[s[i]] == 0;
            if (span > maxspan)
                maxspan = span;
        }
        else
        {
            hashTable[s[i]] = 1;
        }
    }
    return maxspan;
}

int main()
{
    const string a = "abmadsefadd";
    const string a1 = "avoaid";
    cout << getMaxLen(a) << endl;
    cout << getMaxLen(a1) << endl;
}

结果

5

3

字符串中最长的不重合字串长度,布布扣,bubuko.com

字符串中最长的不重合字串长度

标签:style   blog   color   strong   os   for   

原文地址:http://www.cnblogs.com/kaituorensheng/p/3822923.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!