生活随笔
收集整理的這篇文章主要介紹了
LeetCode 3. 无重复字符的最长子串(滑动窗口+哈希)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. 題目
給定一個字符串,請你找出其中不含有重復字符的 最長子串 的長度。
示例 1:
輸入: "abcabcbb"
輸出: 3
解釋: 因為無重復字符的最長子串是 "abc",所以其長度為 3。示例 2:
輸入: "bbbbb"
輸出: 1
解釋: 因為無重復字符的最長子串是 "b",所以其長度為 1。示例 3:
輸入: "pwwkew"
輸出: 3
解釋: 因為無重復字符的最長子串是 "wke",所以其長度為 3。請注意,你的答案必須是 子串 的長度,"pwke" 是一個子序列,不是子串。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
《劍指Offer》同題:面試題48. 最長不含重復字符的子字符串
2. 哈希解題
- 設置start,end窗口
- 檢查字符在哈希表中嗎?不在,插入表中,value為下標
- 在表中則,刪除start到重復的那個位置的hash表中的key
- 更新窗口和maxlen
class Solution {
public:int lengthOfLongestSubstring(string s
) {int i
, j
, k
, start
= 0, end
= 0, maxlen
= 0;unordered_map
<char,int> m
;unordered_map
<char,int>::iterator it
;for(i
= 0; i
< s
.size(); ++i
){it
= m
.find(s
[i
]);if(it
!= m
.end()){k
= it
->second
;for(j
= start
; j
<= k
; ++j
) m
.erase(s
[j
]);start
= k
+1;}m
[s
[i
]] = i
;++end
;if(end
-start
> maxlen
)maxlen
= end
-start
;}return maxlen
;}
};
優化寫法
class Solution {
public:int lengthOfLongestSubstring(string s
) {int i
, k
, start
= 0, end
= 0, maxlen
= 0;unordered_map
<char,int> m
;unordered_map
<char,int>::iterator it
;for(i
= 0; i
< s
.size(); ++i
){it
= m
.find(s
[i
]);if(it
!= m
.end()){k
= it
->second
;start
= max(start
, k
+1);}m
[s
[i
]] = i
;++end
;if(end
-start
> maxlen
)maxlen
= end
-start
;}return maxlen
;}
};
class Solution {
public:int lengthOfLongestSubstring(string s
) {if(s
.empty())return 0;set
<char> set
;int i
= 0, j
= 0, maxlen
= 0;for( ; j
< s
.size(); ++j
){if(!set
.count(s
[j
])){set
.insert(s
[j
]);maxlen
= max(maxlen
,j
-i
+1);}else{while(s
[i
] != s
[j
]){set
.erase(s
[i
++]);}i
++;}}return maxlen
;}
};
class Solution {
public:int lengthOfLongestSubstring(string s
) {unordered_map
<char,int> m
;int maxlen
= 0, i
= 0, j
= 0;while(j
< s
.size()){m
[s
[j
]]++;if(m
[s
[j
]]>1){while(m
[s
[j
]]>1){m
[s
[i
]]--;i
++;}}elsemaxlen
= max(maxlen
,j
-i
+1);j
++;}return maxlen
;}
};
總結
以上是生活随笔為你收集整理的LeetCode 3. 无重复字符的最长子串(滑动窗口+哈希)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。