[LeetCode] Longest Substring Without Repeating Characters

来源:互联网 发布:淘宝买衣服货到付款 编辑:程序博客网 时间:2024/05/16 00:44

原题地址:https://oj.leetcode.com/problems/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.


字符串常用方法,就是维护一个窗口,[left, right],right增加如果还没有重复则继续增加,如果有重复,此时为为当前left开始的不重复子符串的最大长度,比较更新最大值,同时left右移,直到找到和当前right 一样的字符,重新开始。


public class Solution {    public int lengthOfLongestSubstring(String s) {        if (s == null || s.length() < 1) {            return 0;        }                    int left = 0;        int right = 0;        Set<Character> charSet = new HashSet<Character>();        int maxLen = 0;        while (right < s.length()) {            char curChar = s.charAt(right);            if (!charSet.contains(s.charAt(right))) {                charSet.add(s.charAt(right));                            } else {                int curLen = right - left;                if (curLen > maxLen) {                    maxLen = curLen;                }                                while (s.charAt(left) != s.charAt(right)) {                                        charSet.remove(s.charAt(left));                    left++;                }                left++;                            }            right++;        }        maxLen = Math.max(maxLen, right - left);        return maxLen;    }}


0 0
原创粉丝点击