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.
题目含义:获取最长子串,要去子串中没有重复字符
1 public int lengthOfLongestSubstring(String s) { 2 if (s.length() == 0) return 0; 3 HashMap<Character,Integer> map = new HashMap<>(); //记录每个字符最后一次出现的位置 4 int max=0; 5 int j=0; 6 for (int i=0;i<s.length();i++) 7 { 8 char letter = s.charAt(i); 9 if (map.containsKey(letter)) 10 { 11 j = Math.max(j,map.get(letter)+1); //j表示上一个letter后面的字符位置 12 } 13 map.put(letter,i);//记录每个字符最后一次出现的位置 14 max = Math.max(max,i-j+1);//上一个letter后面的字符到i的长度,也就是非重复子串的长度 15 } 16 return max; 17 }