Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: “abcabcbb” Output: 3 Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: “bbbbb” Output: 1 Explanation: The answer is "b", with the length of 1.
Example 3:
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.
classSolution { publicintlengthOfLongestSubstring(String s) { if (s == null || s.length() == 0) { return0; } Map<Character, Integer> map = newHashMap<>(); Queue<Character> q = newLinkedList<>(); intl= s.length(); intmax=0; for (inti=0; i < l; i++) { charc= s.charAt(i); if (map.containsKey(c)) { if (q.size() > max) { max = q.size(); } while(!q.isEmpty()) { chara= q.poll(); map.remove(a); if (a == c) { break; } } } q.offer(c); map.put(c, i); } return q.size() > max ? q.size() : max; } }
官方答案
1 2 3 4 5 6 7 8 9 10 11 12 13
publicclassSolution { publicintlengthOfLongestSubstring(String s) { intn= s.length(), ans = 0; int[] index = newint[128]; // current index of character // try to extend the range [i, j] for (intj=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; } }