[LeetCode]-algorithms-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.
分析:求最大不重复子串的长度
public int lengthOfLongestSubstring(String s) { char[] arr = s.toCharArray(); HashMap<Character,Integer> map = new HashMap<Character,Integer>(); int len = 0; for(int i=0; i<arr.length; i++){ if(map.containsKey(arr[i])){ len = Math.max(len, map.size()); i = map.get(arr[i]); map.clear(); }else{ map.put(arr[i],i); } } len = Math.max(len, map.size()); return len; }
结语:依次把字符串的每个字符以及它对应的下表索引存入到Map中,字符为键,下表索引为值
每插入一次,进行判断,如果存在则从这个重复的字符的下一个开始遍历