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.

讲一下思路,无重复的子串,要解决的问题是快速确定目前字符是否已经重复,这个问题显而易见用hash,所以用hashset存储已经出现的值。

然后通过滑动窗口,当滑到的值没有重复添加到hashset并计算当前长度是否比之前的最大长度大,如果重复则在hashset中删除前面的数,直到

将与当前值重复的值删除。

 1     public int lengthOfLongestSubstring(String s) {
 2         if (s == null) {
 3             return 0;
 4         }
 5         HashSet<Character> set = new HashSet<Character>(s.length());
 6         int result = 0;
 7         int pre = 0;
 8         int last = 0;
 9         while (last < s.length()) {
10             if (set.contains(s.charAt(last))) {//如果包含,从前开始删除直到删除与当前
11                 set.remove(s.charAt(pre));    //相同的那个值
12                 pre++;
13             } else {
14                 set.add(s.charAt(last++));//否则添加当前值并滑到下一个值。
15                 //因为last自增了,所以last-pre为当前长度
16                 result = Math.max(result,last - pre);
17             }
18         }
19         return result;
20     }

 

转载于:https://www.cnblogs.com/zhandouBlog/p/8097985.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值