3. Longest Substring Without Repeating Characters

题目描述

Given a string, find the length of thelongest substringwithout 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 asubstring,"pwke"is asubsequenceand not a substring.

解题方法

注意: 要求為substring, 透過重複計算的結果

Run time complexity: O(n)

    public int lengthOfLongestSubstring(String s){
        //corner case
        if(s == null || s.length() == 0){
            return 0;
        }

        Set<Character> set = new HashSet<>();
        int j = 0;
        int maxLen = 0;
        for(int i = 0 ; i < s.length(); i++){
            while(j < s.length() && !set.contains(s.charAt(j))){
                set.add(s.charAt(j));
                j++;
            }
            maxLen = Math.max(maxLen, j - i);
            set.remove(s.charAt(i));
      }
        return maxLen;
    }

results matching ""

    No results matching ""