Tips:所有代碼實現包含三種語言(java、c++、python3)
題目
Given a string, find the length of the longest substring without repeating characters.
給定字符串,找到最大無重復子字符串。
樣例
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Input: "pwwkew"
Output: 3
Explanation: 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.
解題
首先看到:
輸入:一個字符串
輸出:最大無重復子字符串的長度
優秀的程序猿很快理解了問題,并且快速給出了第一個思路:
計算以字符串中的每個字符作為開頭的子字符串的最大長度,然后選取最大長度返回;
那么問題就變了簡單了:求解字符串中以某個字符開頭的最大無重復子字符串 ,這里我們借助 Set 實現判斷子字符串中是否無重復。
具體步驟如下:
- 遍歷字符串中每個字符,并執行步驟2;
- 構建一個 Set,用于記錄子字符串所包含字符,逐個添加此字符之后的字符進入 Set,直至 Set 中已包含此字符;
- 比較所有無重復子字符串的長度,返回最大值;
//java
// Runtime: 77 ms, faster than 17.83% of Java online submissions for Longest Substring Without Repeating Characters.
// Memory Usage: 39.4 MB, less than 19.93% of Java online submissions for Longest Substring Without Repeating Characters.
public int lengthOfLongestSubstring(String s) {
if(s.length()==0) return 0;
if(s.length()==1) return 1;
char[] schars = s.toCharArray();
int max = 0;
for(int i = 0; i < schars.length; i++){
HashSet<Character> curSet = new HashSet<Character>();
int j = i;
for(; j < schars.length; j++){
if(curSet.contains(schars[j])){
break;
}
curSet.add(schars[j]);
}
max = Math.max(max, j-i);
}
return max;
}
// c++
// Runtime: 900 ms, faster than 6.82% of C++ online submissions for Longest Substring Without Repeating Characters.
// Memory Usage: 271 MB, less than 5.03% of C++ online submissions for Longest Substring Without Repeating Characters.
int lengthOfLongestSubstring(string s) {
if(s.length()==0) return 0;
if(s.length()==1) return 1;
int result = 0;
for(int i = 0; i < s.length() - result; i++){
unordered_set<char> curSet;
int j = i;
for(; j < s.length(); j++){
if(curSet.find(s[j]) != curSet.end()){
break;
}
curSet.insert(s[j]);
}
result = max(result, j-i);
}
return result;
}
# python3
# Runtime: 2456 ms, faster than 5.01% of Python3 online submissions for Longest Substring Without Repeating Characters.
# Memory Usage: 13.4 MB, less than 5.05% of Python3 online submissions for Longest Substring Without Repeating Characters.
def lengthOfLongestSubstring(self, s: str) -> int:
if len(s) == 0: return 0
if len(s) == 1: return 1
result = 0
i = 0
while i < len(s) - result:
j = i
cur_list = []
while j < len(s):
if s[j] in cur_list:
break
cur_list.append(s[j])
j+=1
result = max(result, len(cur_list))
i+=1
return result
可以看到,雖然算法是正確的,但是 runtime 表現很差,優秀的程序猿不滿足于此;
再審視一遍題目:
給定字符串,找到最大無重復子字符串
優秀的程序猿敏銳的捕捉到了兩個關鍵詞 "找到"、"子字符串" ,腦子里猛地蹦出來一個思路:滑動窗口(Sliding Window) ;
滑動窗口(Sliding Window) :設立兩個游標,分別指向字符串中的字符,兩個游標作為窗口的左右邊界用來表示窗口,也就是子字符串;
對于滑動窗口(Sliding Window),我們必須明確以下幾點:
- 窗口代表什么?
- 左右邊界代表什么?
- 左右邊界的滑動時機?
首先我們知道,在本題中,窗口代表的就是無重復子字符串,左右邊界分別代表子字符串的兩端;
對于滑動時機,在本題中,我們限定右邊界的滑動為主滑動,也就是說,右邊界的滑動為從字符串最左端至最右端;而對于左邊界,其滑動跟隨右邊界的滑動,每當右邊界發生滑動,那么判斷新納入字符是已存在當前窗口中,如不存在,左邊界不動,如存在,則將左邊界滑動至窗口中此已存在字符之后,可看出此操作保證了窗口中一定不存在重復字符;
每當窗口發生變化,更新最大窗口長度,當右邊界滑動至字符串最右端時結束并返回最大長度;
隨著右邊界的滑動,我們使用 map 記錄每個字符最后出現的位置,以便于左邊界的滑動更新;
// java
// Runtime: 17 ms, faster than 96.07% of Java online submissions for Longest Substring Without Repeating Characters.
// Memory Usage: 39.1 MB, less than 23.13% of Java online submissions for Longest Substring Without Repeating Characters.
public int lengthOfLongestSubstring(String s) {
if(s == null || s.length()==0) return 0;
if(s.length()==1) return 1;
char[] schars = s.toCharArray();
Map<Character, Integer> sMap = new HashMap<>();
int max = 0;
int start=0, end=0;
for(; end < schars.length; end++){
if(sMap.containsKey?(schars[end])){
start = Math.max(start, sMap.get(schars[end]));
}
sMap.put(schars[end], end+1);
max = Math.max(max, end-start+1);
}
return max;
}
// c++
// Runtime: 28 ms, faster than 67.81% of C++ online submissions for Longest Substring Without Repeating Characters.
// Memory Usage: 16.3 MB, less than 52.86% of C++ online submissions for Longest Substring Without Repeating Characters.
int lengthOfLongestSubstring(string s) {
if(s.length()==0) return 0;
if(s.length()==1) return 1;
int result = 0;
unordered_map<char, int> sMap;
int start=0, end=0;
for(; end < s.length(); end++){
if(sMap.count(s[end])){
start = max(start, sMap[s[end]]);
}
sMap[s[end]] = end+1;
result = max(result, end-start+1);
}
return result;
}
# python3
# Runtime: 92 ms, faster than 63.67% of Python3 online submissions for Longest Substring Without Repeating Characters.
# Memory Usage: 13.5 MB, less than 5.05% of Python3 online submissions for Longest Substring Without Repeating Characters.
def lengthOfLongestSubstring(self, s: str) -> int:
if len(s) == 0: return 0
if len(s) == 1: return 1
result = 0
s_dict = {}
start = 0
for idx, ch in enumerate(s):
if ch in s_dict:
start = max(start, s_dict[ch])
s_dict[ch] = idx+1
result = max(result, idx-start+1)
return result
runtime 表現不錯,不過優秀的程序猿覺得任有瑕疵,既然我們處理的數據被限定為字符串,那我們其實沒必要使用 map ,使用長度為 256 的數組就完全可以起到 map 的作用;
優秀的程序猿又歡快的修改了答案
// java
// Runtime: 15 ms, faster than 99.32% of Java online submissions for Longest Substring Without Repeating Characters.
// Memory Usage: 40 MB, less than 13.57% of Java online submissions for Longest Substring Without Repeating Characters.
public int lengthOfLongestSubstring(String s) {
if(s == null || s.length()==0) return 0;
if(s.length()==1) return 1;
char[] schars = s.toCharArray();
int[] lastIndex = new int[256];
int max = 0;
int start = 0, end = 0;
for(; end < schars.length; end++){
start = Math.max(start, lastIndex[(int)schars[end]]);
lastIndex[(int)schars[end]] = end+1;
max = Math.max(max, end-start+1);
}
return max;
}
// c++
// Runtime: 16 ms, faster than 99.18% of C++ online submissions for Longest Substring Without Repeating Characters.
// Memory Usage: 14.6 MB, less than 97.14% of C++ online submissions for Longest Substring Without Repeating Characters.
int lengthOfLongestSubstring(string s) {
if(s.length()==0) return 0;
if(s.length()==1) return 1;
int result = 0;
int lastIndex[256];
memset(lastIndex, 0x00000000, sizeof(int)*256);
int start=0, end=0;
for(; end < s.length(); end++){
start = max(start, lastIndex[s[end]]);
lastIndex[s[end]] = end+1;
result = max(result, end-start+1);
}
return result;
}
# python3
# Runtime: 92 ms, faster than 63.67% of Python3 online submissions for Longest Substring Without Repeating Characters.
# Memory Usage: 13.5 MB, less than 5.05% of Python3 online submissions for Longest Substring Without Repeating Characters.
def lengthOfLongestSubstring(self, s: str) -> int:
if len(s) == 0: return 0
if len(s) == 1: return 1
result = 0
lastIndex = [0 for i in range(256)]
start = 0
for idx, ch in enumerate(s):
start = max(lastIndex[ord(ch)], start)
lastIndex[ord(ch)] = idx+1
result = max(result, idx-start+1)
return result
優秀的程序猿又嚴謹得審視了幾遍代碼,滿意得合上了電腦。。。