您的位置:首页 > 其它

leetcode——Longest Substring Without Repeating Characters 求链表中无重复字符的最大字串长度(AC)

2014-06-06 21:03 483 查看
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without
repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

为了提升时间效率,我开辟了一个长度为256的整型数组来标识子串中的字符是否重复,避免了采用循环比较的方法来判定字符是否重复。需要注意的是当我们发现一个字符与当前子串中的字符重复时,此时新的字串需要从子串中第一次出现此字符位置的后一个字符开始作为新的子串的起点,代码中采用了一个整型变量来记录判定过程中的最大子串长度。代码如下:

class Solution {
public:
int lengthOfLongestSubstring(string s)
{
int length = s.length(),maxValue=0,count=0;
int flag[256];
Reset(flag);
for(int i=0; i<length; i++)
{
if(flag[s[i]] == -1)
{
count++;
flag[s[i]] = i;
}
else
{
i = flag[s[i]]+1;
Reset(flag);
flag[s[i]] = i;
count=1;
}
if(maxValue < count)
maxValue = count;
}
return maxValue;
}
void Reset(int *flag)
{
for(int i = 0; i<256; i++)
flag[i] = -1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  substring 子串 长度
相关文章推荐