|
亲!马上注册或者登录会查看更多内容!
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
本帖最后由 MengMa 于 12-12-2014 08:46 PM 编辑
Longest Substring Without Repeating Characters
思路:max存当前最长的无重复子串长度。HashSet存当前的最长无重复子串里包含的字符。
滑动窗口:
用两个指针访问数组:一个快指针,一个慢指针。
简单记法:快指针 吃 字符,慢指针 吐 字符。
快指针一直往右走,尽可能的把没有出现的字符加入到HashSet里。
当出现了重复字符时,即HashSet中已经包含了当前的fast指向的字符,fast指针 停止。
这时候要进行下列处理:
首先记录当前长度,如果比已有max长,则更新max。
否则slow指针开始吐字符,当charAt(slow)并非重复字符时,slow++,直到停止在charAt(slow) == charAt(fast)
这时候不要忘记再slow++一次。确保窗口里只出现一次charAt(fast)那个字符。
时间 O(n) 空间 O(n)
代码:
- 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 slow = 0;
- int fast = 0;
- while(fast < s.length())
- {
- if(!set.contains(s.charAt(fast)))
- {
- set.add(s.charAt(fast));
- }
- else
- {
- max = Math.max(max, fast - slow);
- while(s.charAt(slow) != s.charAt(fast))
- {
- set.remove(s.charAt(slow));
- slow ++;
- }
- slow ++;
- }
- fast ++;
- }
- max = Math.max(max, fast - slow);
- return max;
- }
- }
复制代码
|
|