Given a string, find the length of the longest substring without repeating characters. for example, the longest substring without repeating letters for "abcabcbb" is "ABC", which the length is 3. for "bbbbb" the longest substring is "B", with the length of 1.
Question: greedy algorithm.
Use a hashmap to store the elements of the longest unduplicated substring. The variable leftbound stores the leftmost boundary of the current state. The character s [I] currently traversed has two situations:
- S [I] indicates that the element already exists in the map, so move leftbound left until leftbound reaches I, this section does not contain S [I], in addition, the elements scanned by leftbound are cleared in map;
- The elements referred to by S [I] are not in the map. Keep leftbound unchanged and check whether the length of the longest substring needs to be updated.
The Code is as follows:
1 public class Solution { 2 public int lengthOfLongestSubstring(String s) { 3 if(s == null || s.length() == 0) 4 return 0; 5 6 HashMap<Character, Integer> map = new HashMap<Character, Integer>(); 7 int leftebound = 0; 8 int answer = 0; 9 10 for(int i = 0;i < s.length();i++){11 char current = s.charAt(i);12 if(map.containsKey(s.charAt(i))){ 13 while(s.charAt(leftebound) != current && leftebound < i){14 map.remove(s.charAt(leftebound));15 leftebound++;16 }17 leftebound++;18 }19 else {20 map.put(current, 0);21 answer = Math.max(i-leftebound+1, answer);22 }23 }24 25 return answer; 26 }27 }