3. Longest Substring Without Repeating Characters

101 阅读1分钟

Given a string s, find the length of the longest substring without repeating characters.

Example 1:

Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.

Example 2:

Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.

Example 4:

Input: s = ""
Output: 0

Constraints:

  • 0 <= s.length <= 5 * 10<sup>4</sup>

  • s consists of English letters, digits, symbols and spaces.

    class Solution { public int lengthOfLongestSubstring(String s) { int max=0; Map<Character,Integer> mp=new HashMap(); int index=0;int i=0; for(;i<s.length();i++){ if(mp.get(s.charAt(i))==null || mp.get(s.charAt(i))<index){ mp.put(s.charAt(i),i); max=Math.max(max,i-index+1);

            }else if(mp.get(s.charAt(i))<i && mp.get(s.charAt(i))>=index){
                max=Math.max(max,i-index);
                index=mp.get(s.charAt(i))+1;
                mp.put(s.charAt(i),i);
            }
        }
        max=Math.max(max,i-index);
        return max;
    }
    

    }

159. Longest Substring with At Most Two Distinct Characters

Given a string s, find the length of the longest substring 

that contains at most 2 distinct characters.

Example 1:

Input: "eceba"
Output: 3
Explanation: tis "ece" which its length is 3.

Example 2:

Input: "ccaabbb"
Output: 5
Explanation: tis "aabbb" which its length is 5.

public static int subarraysWithKDistinct(String s) {
        int max=0;
        Map<Character,Integer> mp=new HashMap();
        int index=0;int i=0;
        for(;i<s.length();i++){
            mp.put(s.charAt(i),i);
            while(mp.size()>2){
                if(mp.get(s.charAt(index))==index) mp.remove(s.charAt(index));
                ++index;

            }
            max=Math.max(max,i-index+1);
        }
        max=Math.max(max,i-index);
        return max;

    }