leetcode題解-3、Longest Substring Without Repeating Characters
題意:給定一個字串,求最長不重複子串(非子序列)。
例子:
Input: “abcabcbb”
Output: 3
分析: “abc”, 它的長度為 3.
Input: “bbbbb”
Output: 1
分析: “b”, 它的長度為 1.
Input: “pwwkew”
Output: 3
分析: The answer is “wke”, with the length of 3.
注意:子串(substring)和子序列(subsequence )的區別, “pwke” 是一個子序列而不是子串。
分析:最長不重複子串有三種解法。
1、暴力解
2、雙指標
3、雙指標優化解
1、暴力解
逐個檢查所有子字串,看它是否沒有重複的字元。
時間複雜度
空間複雜度,是字元的種類數,是字串的長度。
public class Solution {
public int lengthOfLongestSubstring(String s) {
int n = s.length();
int ans = 0;
for (int i = 0; i < n; i++)
for (int j = i + 1; j <= n; j++)
if (allUnique(s, i, j)) ans = Math.max(ans, j - i);
return ans;
}
public boolean allUnique(String s, int start, int end) {
Set<Character> set = new HashSet<>();
for (int i = start; i < end; i++) {
Character ch = s.charAt(i);
if (set .contains(ch)) return false;
set.add(ch);
}
return true;
}
}
2、雙指標法
暴力求解時間複雜度顯然不能接受。那麼用HashSet將字元儲存在當前視窗[i,j)中(初始化j = i)。 然後將索引j向右滑動。 如果它不在HashSet中,我們進一步向右滑動j。 這樣做直到s [j]已經在HashSet中。 此時,我們就找到了以s[i]開頭的無重複字元的子字串的最大長度。 如果對所有s[i]重複上述步驟,就可以得到全域性最大長度。
時間複雜度
空間複雜度,是字元的種類數,是字串的長度。
public static int lengthOfLongestSubstring(String s) {
int len = s.length();
int maxLen = 0;
HashSet<Character> set = new HashSet<Character>();
int i = 0;
int j = 0;
int count = 0;
while(i < len && j < len){
if(set.contains(s.charAt(j))){
set.remove(s.charAt(i++));
count--;
}else{
set.add(s.charAt(j++));
count++;
}
maxLen = Math.max(count, maxLen);
}
return maxLen;
}
3、雙指標方法的優化
方案2最多需要2n步。 實際上,它可以優化為僅需要n步。我們可以使用map來定義字元到其索引的對映,而不是使用set來判斷字元是否存在。 然後,當我們找到重複的字元時,我們可以立即跳過重複的字元。
如果s[j]在[i,j)的範圍內有一個重複的字元s[j’],我們不需要對索引i一步一步的增加,我們可以直接跳過[i,j’],令i=j’+1即可。
時間複雜度
空間複雜度,是字元的種類數,是字串的長度。
public class Solution {
public int lengthOfLongestSubstring(String s) {
int n = s.length(), ans = 0;
Map<Character, Integer> map = new HashMap<>(); // current index of character
// try to extend the range [i, j]
for (int j = 0, i = 0; j < n; j++) {
if (map.containsKey(s.charAt(j))) {
i = Math.max(map.get(s.charAt(j)), i);
}
ans = Math.max(ans, j - i + 1);
map.put(s.charAt(j), j + 1);
}
return ans;
}
}