第三道题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.
图一、本题窗口扫描示意图
思路:如上图(画得不好请见谅)。维护一个窗口[walker,runner]:
一、窗口区间上限runner跑在前面,每扫描一次,将对应的元素添加至HashSet里,直到扫描到HashSet里已经存在的元素,runner停下,记为runner1。等一等走得比较慢的walker。此时,窗口内存在与walker处相同的元素;
二、首先记录walker与runner的距离,因为此时walker往前的子字符串都是无元素重复的,与max比大小。紧接着,walker也不能落后,走了起来,一直到与runner一样元素的地方。边走边把之前那些元素从HashSet里丢掉,直到找到那个与runner1元素相同的地方,记为walker1。walker1前面部分丢掉的原因是不可能找到一个包含[walker1,runner1]区间的再大的区间使得其实无重复的,因为[walker1,runner1]区间内已有重复元素。所以求下一个目标区间只能往前走,把下区间丢掉,此时去到第三步;
三、把walker1前面(包括自身)丢掉后,问题回到了第一步,重复第一步的过程即可。
Java代码如下;
public class Solution { public int lengthOfLongestSubstring(String s) { if(s==null && s.length()==0) return 0; HashSet<Character> set = new HashSet<Character>(); int max = 0; int walker = 0; int runner = 0; for(;runner<s.length();runner++) { if(set.contains(s.charAt(runner))) { max = (runner-walker)>max?(runner-walker):max; while(s.charAt(walker)!=s.charAt(runner)) { set.remove(s.charAt(walker)); walker++; } walker++; } else { set.add(s.charAt(runner)); } } max = (runner-walker)>max?(runner-walker):max; return max; } }
学习参考:
[1]. LeetCode – Longest Substring Without Repeating Characters (Java)
[2]. Repeating Characters -- LeetCode