1. 程式人生 > >[LeetCode] Longest substring without repeating characters 最長無重復子串

[LeetCode] Longest substring without repeating characters 最長無重復子串

log 技術 pan -i 一個 html https rep tor

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.

題意:給定字符串找到最大無重復子串。

思路:參考LeetCode中提交的答案。使用哈希表的思想,建立一個256位大小的整型數組來代替哈希表(原因不知,博友Grandyang給出的原因是是ASCII表共能表示256個字符,所以可以記錄所有字符。)哈希表中,在沒有遇到重復字符之前,將當前字符對應的值賦為其在給定串s中的下標;當遇到重復字符時,因,該重復字符對應的值(即該字符的下標)大於上一串沒有重復字符的起點下標,所以更新新子串的起點(深刻理解這句話

),並記下此時的maxLen值。我們以s="abcabcb"為例,分析整個過程。當遍歷到第二個 "a"時,m[s[i]]=0>-1 ,所以,start=0,同理可以更新後面的字符對應的值,更新過程用圖表示如下:

技術分享

代碼如下:

 1 class Solution {
 2 public:
 3     int lengthOfLongestSubstring(string s) 
 4     {
 5         vector<int> m(256,-1);
 6         int maxLen=0,start=-1;
 7         for(int i=0;i<s.size();++i)
8 { 9 if(m[s[i]]>start) 10 start=m[s[i]]; 11 m[s[i]]=i; 12 maxLen=max(maxLen,i-start); 13 } 14 return maxLen; 15 } 16 };

註意:兩部分不重復子串存在交叉的情況。不能使用這樣的思路:記錄兩字符中間的長度,然後以第二字符為開始遍歷得到新的字符,因為若是有交叉的情況,如abcade,abc和bcade存在交叉,返回值應該是5(bcade),不是3(abc或者ade)。

[LeetCode] Longest substring without repeating characters 最長無重復子串