LeetCode, leetcodeoj
1 public int lengthOfLongestSubstring (String s) {2 char [] chars = s. toCharArray ();
3 // store position 4 HashMap <Character, Integer> map = new HashMap <Character, Integer> ();
5 // when traversing to the I position, lastNoRepeatIndex to I is part of the already traversed element that does not have repeated elements 6 // For example: abcdeefghij, when traversing to the g element, lastNoRepeatIndex = 5; that is, the location of the Second e is 7 int lastNoRepeatIndex = 0;
8 // subscript 9 int [] longestIndex = {0, 0 };
10 // Maximum length of the nth string 11 int longestLength = 0; 12 13 int len = 0; 14 15 for (int I = 0; I <chars. length; I ++) {16 // abcdeefghiijk, update lastNoRepeatIndex from 5 to 1017 if (map. containsKey (chars [I]) & map. get (chars [I]) + 1> lastNoRepeatIndex) {18 lastNoRepeatIndex = map. get (chars [I]) + 1; 19} 20 map. put (chars [I], I); 21 len = I-lastNoRepeatIndex + 1; 22 if (len> longestLength) {23 longestLength = len; 24 longestIndex [0] = lastNoRepeatIndex + 1; 25 longestIndex [1] = I; 26} 27} 28 return longestLength; 29}