問題
給定一個字符串,請你找出其中不含有重復字符的 最長子串 的長度。
示例 1:
輸入: "abcabcbb"
輸出: 3
解釋: 因為無重復字符的最長子串是 "abc",所以其長度為 3。
示例 2:
輸入: "bbbbb"
輸出: 1
解釋: 因為無重復字符的最長子串是 "b",所以其長度為 1。
示例 3:
輸入: "pwwkew"
輸出: 3
解釋: 因為無重復字符的最長子串是 "wke",所以其長度為 3。
請注意,你的答案必須是 子串 的長度,"pwke" 是一個子序列,不是子串。
解答
使用滑動窗口思路. 已知子串長度為n, 窗口開始位置為i=0, 結束位置為j=0,使用一個集合存儲字符元素, 循環字符串(j++), 當集合中存在字符時說明出現了重復子串, 此時的非重復串長度為j-i, 同時開始位置移動(i++);
僅需要做一次遍歷, 時間復雜度為O(n).
代碼
使用HashMap.
public static int lengthOfLongestSubString(String s) {
if (s == null || s.length() == 0) {
return 0;
}
int rs =0;
int left = 0;
HashMap<Character,Integer> map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
if (map.containsKey(s.charAt(i))){
left = Math.max(left,map.get(s.charAt(i))+1);
}
map.put(s.charAt(i),i);
rs = Math.max(rs,i+1-left);
}
return rs;
}
使用HashSet
public static int lengthOfLongestSubStringSet(String s) {
if (s == null || s.length() == 0) {
return 0;
}
int rs = 0, i = 0, j = 0;
int length = s.length();
HashSet<Character> set = new HashSet<>();
while (i < length && j < length) {
if (!set.contains(s.charAt(j))){
set.add(s.charAt(j));
j++;
rs = Math.max(rs,j-i);
}else{
set.remove(s.charAt(i));
i++;
}
}
System.out.println(set);
return rs;
}