[LeetCode] Longest Substring Without Repeating Characters
[题目]
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb"
, the answer is "abc"
, which the length is 3.
Given "bbbbb"
, the answer is "b"
, with the length of 1.
Given "pwwkew"
, the answer is "wke"
, with the length of 3. Note that the answer must be a substring, "pwke"
is a subsequence and not a substring.
[解题思路0]
扫描遇到重复字母时,以上一个重复字母的index + 1,作为新的搜索起始位置。
[解题思路1]
使用LinkedHashSet作为移动窗口,这样可以节省空间
代码如下:
1 public int lengthOfLongestSubstring(String s) { 2 if (s.length() == 0) return 0; 3 int ret = 1; 4 Set<Character> set = new LinkedHashSet<Character>(); 5 int[] maxEndsWith = new int[s.length()]; 6 maxEndsWith[0] = 1; 7 set.add(s.charAt(0)); 8 for (int i = 1; i < s.length(); ++i) { 9 char c = s.charAt(i); 10 if (!set.contains(c)) { 11 set.add(c); 12 maxEndsWith[i] = maxEndsWith[i - 1] + 1; 13 } else { 14 Iterator<Character> it = set.iterator(); 15 while (it.hasNext()) { 16 char front = it.next(); 17 it.remove(); 18 if (front == c) break; 19 } 20 set.add(c); 21 maxEndsWith[i] = set.size(); 22 } 23 ret = Math.max(maxEndsWith[i], ret); 24 } 25 return ret; 26 }