Question
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.
Solution
Use extra map to record whether the character has appeared. Remember to consider the situation of last character. Time complexity O(n), space cost O(n).
1 public class Solution { 2 public int lengthOfLongestSubstring(String s) { 3 if (s == null || s.length() < 1) 4 return 0; 5 Map<Character, Integer> map = new HashMap<Character, Integer>(); 6 char[] copy = s.toCharArray(); 7 int length = s.length(); 8 int maxCount = 1; 9 char start = s.charAt(0); 10 for (int i = 0; i <= length; i++) { 11 char tmp; 12 if (i == length) { 13 tmp = s.charAt(length - 1); 14 } else { 15 tmp = s.charAt(i); 16 } 17 if (!map.containsKey(tmp)) { 18 map.put(tmp, i); 19 } else { 20 int startIndex = map.get(start); 21 int dupIndex = map.get(tmp); 22 if (startIndex <= dupIndex) { 23 if (dupIndex < length - 1) 24 start = s.charAt(dupIndex + 1); 25 maxCount = Math.max(maxCount, i - startIndex); 26 } 27 map.put(tmp, i); 28 } 29 } 30 return maxCount; 31 } 32 }