leetcode3——无重复字符的最长子串——java实现

题目要求:
leetcode3——无重复字符的最长子串——java实现_第1张图片
分析:
由于不能重复,所以首先就考虑到利用HashSet,HashSet底层利用的也是HashMap,但是HashSet中的内容不能重复。
由于返回的值是子串的长度,所以需要定义一个count来计数。

1.根据滑动窗口的思想,定义start和end两个变量,它们在最开始时均指向字符串s的第一个字符;
2.定义一个HashSet,用来存放符合题目条件的子串;
3.对整个字符串s的每个字符开始遍历(使用charAt方法):
一旦遍历到的字符与我们的HashSet中出现相同的字符,则就将HashSet中最初的值给丢弃掉,并将start++;
如果没有出现相同的字符,则继续遍历,并将end++。此时还要统计在HashSet中有几个字符了,利用Math中的max方法;
4.遍历完成之后,返回统计值即可。

具体代码如下所示:

  public class Solution {
    public int lengthOfLongestSubstring(String s) {
        Set set = new HashSet<>();        
        int count = 0, start = 0, end = 0;        
        while (start < s.length() && end < s.length()) {
            if (!set.contains(s.charAt(end))) {
                set.add(s.charAt(end));
                end ++;
                count = Math.max(count, end - start);       
            } else {
                set.remove(s.charAt(start));
                start ++;
            }
        }
        return count;
    }
}

你可能感兴趣的:(leecode)