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.
题意:求一个字符串中不含重复字符的最长子串的长度。
思路:
1. 用一个Map用于记录每个字符出现的位置,记为letterMap;设当前不含重复字符的最长子串起始位置为start;初始时start=0;
2. 如果当前字符C不在letterMap中,或者当前字符在letterMap中记录的位置k<start;
说明从start开始没有与当前字符C重复的字符,把C的位置加入到letterMap中;
3. 如果C在letter中记录的位置k>=start;
说明从start开始有与当前字符C重复的字符;
此时需要更新最大字符串长度,重新设置起始位置start,并将C的位置更新到letterMap中;
4. 最后返回最大长度maxLength;
代码如下:
public int lengthOfLongestSubstring(String s) { if(s == null || "".equals(s)) return 0; int maxLength = 0; Map<Character, Integer> letterMap = new HashMap<Character, Integer>(); int start = 0; for(int i=start; i<s.length(); ) { if(!letterMap.containsKey(s.charAt(i)) || letterMap.get(s.charAt(i)) < start) { letterMap.put(s.charAt(i), i + 1); i++; } else { maxLength = Math.max(maxLength, i-start); start = letterMap.get(s.charAt(i)); letterMap.put(s.charAt(i), i + 1); i++; } } return maxLength > s.length()-start ? maxLength : s.length()-start; }
LeetCode-3 Longest Substring Without Repeating Characters
原文:http://www.cnblogs.com/linxiong/p/4348857.html