3. 无重复字符的最长子串
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:
输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例 3:
输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
解题思路
- 字符串为0或1的时候可以直接返回对应结果。
- 设一个
max_len = 0
,记录字符串中出现的最长不重复子串的长度。 - 使用一个
count_len
记录正在访问的子串的最大长度。 - 类似
KMP
算法的思想,使用repeat_loc
数组记录已访问字符的下一个位置ipos+1
。 - 使用桶排序记录已访问字符,如果正在访问的字符是已访问字符,那么将访问位置
repeat_loc[s[ipos]]
。 - 如果正在访问的字符是已访问字符,将
count_len
与max_len
比较并根据条件赋值,重置count_len = 1
,并置空桶排序记录和位置记录。
解题代码(C语言)
int lengthOfLongestSubstring(char *s){
int str_len = strlen(s);
if(str_len == 0) return 0;
if(str_len == 1) return 1;
int maxn_len = 0,count_len = 1,ipos = 1;
int count_setp[255];
int repeat_loc[255];
memset(count_setp,0,sizeof(count_setp));
memset(repeat_loc,0,sizeof(repeat_loc));
count_setp[s[0]]++;
repeat_loc[s[0]]=1;
while(ipos < str_len)
{
if(s[ipos]!=s[ipos-1] && count_setp[s[ipos]] == 0)
{
count_len++;
count_setp[s[ipos]]++;
repeat_loc[s[ipos]] = ipos+1;
ipos++;
}
else
{
maxn_len = maxn_len > count_len ? maxn_len : count_len;
count_len = 1;
memset(count_setp,0,sizeof(count_setp));
ipos = repeat_loc[s[ipos]];
memset(repeat_loc,0,sizeof(repeat_loc));
count_setp[s[ipos]]++;
repeat_loc[s[ipos]]=ipos+1;
ipos++;
}
}
maxn_len = maxn_len > count_len ? maxn_len : count_len;
return maxn_len;c
}