Longest substring without repeating characters
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.
Algorithm analysis:
Thought 1:
Obtain all the substrings using the most earthy method, and then obtain the longest non-repeated substrings. No need to try, definitely timeout
Idea 2:
Maintain a map and key to store characters and values to store their subscript in S. When you encounter a previous character (the following table is J), update the starting subscript begin of the substring to J + 1. Maintain maxlength at the same time;
The Code is as follows:
1 public int lengthOfLongestSubstring(String s) { 2 int length = s.length(); 3 Map<Character,Integer> hash = new HashMap<Character,Integer>(); 4 int currentLength = 0; 5 int maxLength = 0; 6 int from = 0; 7 for(int i = 0; i < length; i++){ 8 if(!hash.containsKey(s.charAt(i))){ 9 currentLength++;10 hash.put(s.charAt(i), i);11 }else{12 if(from <= hash.get(s.charAt(i))){13 from = hash.get(s.charAt(i)) + 1;14 currentLength = i - hash.get(s.charAt(i));15 }else{16 currentLength++;17 }18 hash.put(s.charAt(i), i);19 }20 if(currentLength > maxLength){21 maxLength = currentLength;22 }23 }24 return maxLength;25 }View code
Thought 2 optimization:
1 public class Solution { 2 public int lengthOfLongestSubstring(String s) { 3 if (s == null || s.length() == 0) 4 return 0; 5 int[] hash = new int[256]; 6 Arrays.fill(hash, -1); 7 int maxLength = 0; 8 int pre = -1; 9 for (int i = 0; i < s.length(); i++) {10 if (hash[s.charAt(i)] > pre) {11 pre = hash[s.charAt(i)];12 }13 maxLength = Math.max(maxLength, i - pre);14 hash[s.charAt(i)] = i;15 }16 return maxLength;17 }18 }