鏈接:
https://leetcode.com/problems/longest-substring-without-repeating-characters/
原題:
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", 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.
分析:
這道題方式還是要使用雙指針的方式,兩個游標,同時維護一個集合,一個游標標注左側index 一個游標標注右側index,在兩游標之間不能出現重復字符,當無重復的時候移動右側游標,一旦移動到重復移動左側游標,在此過程中記錄最大長度。
public class Solution {
public int lengthOfLongestSubstring(String s) {
int j = 0;
int length = 0;
if(s.equals("")) {
return 0;
}
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
while (j < s.length() && (map.get(s.charAt(j))==null || map.get(s.charAt(j)) == 0)) {
map.put(s.charAt(j), 1);
length = Math.max(j-i, length);
j++;
}
map.put(s.charAt(i),0);
}
return length+1;
}
}