首页 > 代码库 > LeetCode ---Longest Substring Without Repeating Characters

LeetCode ---Longest Substring Without Repeating Characters

 1 public int lengthOfLongestSubstring(String s) {
 2     char[] chars = s.toCharArray();
3 //存储已遍历的元素中相应char值最后出现的位置 4 HashMap<Character, Integer> map = new HashMap<Character, Integer>();
5 //当遍历到i位置时,lastNoRepeatIndex到i是已遍历元素中没有重复元素出现的部分 6 //如:abcdeefghij,当遍历到g元素,lastNoRepeatIndex=5;即第二个e的位置 7 int lastNoRepeatIndex = 0;
8 //最长子串的前后位置下标 9 int[] longestIndex = {0, 0};
10 //最长子串长度 11 int longestLength = 0; 12 13 int len = 0; 14 15 for(int i = 0; i < chars.length; i ++) { 16 //abcdeefghiijk,遍历到i=10时,将lastNoRepeatIndex从5更新到10 17 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 }

 

LeetCode ---Longest Substring Without Repeating Characters