給定一個字符串,請你找出其中不含有重復字符的?最長子串?的長度。
示例?1:
輸入: "abcabcbb"
輸出: 3?
解釋: 因為無重復字符的最長子串是 "abc",所以其長度為 3。
示例 2:
輸入: "bbbbb"
輸出: 1
解釋: 因為無重復字符的最長子串是 "b",所以其長度為 1。
示例 3:
輸入: "pwwkew"
輸出: 3
解釋: 因為無重復字符的最長子串是?"wke",所以其長度為 3。
?? ? 請注意,你的答案必須是 子串 的長度,"pwke"?是一個子序列,不是子串。
思路:
一個set記錄i到j遇到的所有字母。
兩個指針,符合條件就更新答案,并且右指針向右。
不符合就刪除左指針相應的值,?并繼續嘗試。
public class Solution {public int lengthOfLongestSubstring(String s) {int n = s.length();Set<Character> set = new HashSet<>();int ans = 0, i = 0, j = 0;while (i < n && j < n) {// try to extend the range [i, j]if (!set.contains(s.charAt(j))){set.add(s.charAt(j++));ans = Math.max(ans, j - i);}else {set.remove(s.charAt(i++));}}return ans;}
}
優化
第一:可以用map記錄一下遇到的char的下標是多少,這樣我們縮i的時候不用一個一個縮,而是直接到該去的位置
第二:可以不用map,因為字符種類有限,用數組記錄(桶排序思想)
public class Solution {public int lengthOfLongestSubstring(String s) {int n = s.length(), ans = 0;int[] index = new int[128];for (int j = 0, i = 0; j < n; j++) {i = Math.max(index[s.charAt(j)], i);ans = Math.max(ans, j - i + 1);index[s.charAt(j)] = j + 1;}return ans;}
}
?