3. Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given
"abcabcbb"
, the answer is"abc"
, which the length is 3.Given
"bbbbb"
, the answer is"b"
, with the length of 1.Given
"pwwkew"
, the answer is"wke"
, with the length of 3. Note that the answer must be a substring,"pwke"
is a subsequence and not a substring.
代码
class Solution {
public:
int lengthOfLongestSubstring(string s)
{
int dict[256];
memset(dict, -1, sizeof(dict));
int maxLen = 0, start = -1;
for (int i = 0; i < s.length(); i++)
{
if(dict[s[i]] > start)
{
start = dict[s[i]];
}
dict[s[i]] = i;
maxLen = max(maxLen, i - start);
}
return maxLen;
}
};
思路
在遍历整个字符串时,记录已经遍历过的每个字符在字符串中最后一次出现的位置,同时保存当前不存在重复字符的最长字符串(smax)的初始位置和当前最长长度(maxLen),如果当前字符(c)已经在smax中,则表示当前的smax已经结束,通过比较判断是否更新相应数值。
实现
首先,为了记录每个字符最后一次出现的位置,新建一个整形数组dict[256],长度256是ascii码的长度,涉及到字符处理的为题,如果需要这样的数组,长度足够,并通过memset函数赋值为-1,-1表示字符还没有在字符串中出现过,由于memset函数是通过字节赋值的,对于整形数组来说只能赋值为-1和0,否则不会达到效果。
然后初始化一些需要用到的变量,maxLen顾名思义,就是当前最长的无重复字符的字符串长度;start是当前正在积累中的最长无重复字符串的开始位置。
接下来就开始遍历字符串,设当前字符为c,每次循环都要更新c在dict数组中的值为当前的位置,然后重新计算maxLen的值,并比较判断是否需要更新值。如果在更新dict数组前,c在dict数组中的值大于start的值,这就意味着c已经在当前正在计数的最长无重复字符串中出现过,这一次的出现造成了重复,需要重新计数,所以将start赋值为c上一次出现的位置,由于maxLen的比较在上一次循环中已经进行,所以不需要处理。
循环结束后maxLen即为所求,返回即可。