题解 | #最长不含重复字符的子字符串#

最长不含重复字符的子字符串

https://www.nowcoder.com/practice/48d2ff79b8564c40a50fa79f9d5fa9c7

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param s string字符串
     * @return int整型
     */
    public int lengthOfLongestSubstring (String s) {
        if (s.length() < 2) {
            return s.length();
        }

        //通过左右指针维护滑动窗口的位置
        int left = 0, right = 0;
        int longest = 0;

        //记录窗口内的元素
        HashSet<Character> set = new HashSet<>();
        char[] chars = s.toCharArray();

        while (right < chars.length) {
            char current = chars[right];
            //右指针遇到重复元素时,左指针移动到最近的重复元素的下一位
            while (set.contains(current)) {
                set.remove(chars[left]);
                left += 1;
            }

            //右指针
            set.add(current);
            longest = Math.max(right - left + 1, longest);
            right++;
        }

        return longest;
    }
}

#在找工作求抱抱##我的求职思考#
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务