您的位置:首页 > 其它

003 Longest Substring Without Repeating Characters [Leetcode]

2015-11-09 14:45 453 查看
题目内容:

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.

解题思路:

顺序遍历,使用hash表记录已经读到过的字母。

由于ASCII码足够表示所有字符了,使用一个长度为128的数组记录出现的下标即可。

每次读到重复的数字时,不重复字符串的起始位置就变为hash表中记录的下标的后一位,并更新最长字符串长度和hash表中记录的当前字母的下标。

时间复杂度为O(n)。

代码:

class Solution
{
public:
int lengthOfLongestSubstring(string s)
{
if(s == "")
return 0;

int l = 0, r = 0, maxl = 0;
unsigned char cset[128];
memset(cset, 0, 128*sizeof(unsigned char));

while(r < s.size())
{
if(cset[s[r]] == 0)
cset[s[r]] = 1;
else
{
maxl = max(maxl, r - l);
while(s[r] != s[l])
{
cset[s[l]] = 0;
++ l;
}
++ l;
}
++ r;
}
maxl = max(maxl, r - l);

return maxl;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: