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
}