Welcome to "Coding Center"!! Coding Center is the place where you will find something new to learn about Java and Python. If you are looking to brush up on your skills before going for an interview, this article is for you...

 Longest Substring Without Repeating Characters


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.

Solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
 class Solution {
    public int lengthOfLongestSubstring(String s) {
        int right = 0;
        int left = 0;
        Set<Character> set = new HashSet<>();
        int maxLength = 0;
        
        while (left < s.length() && right < s.length()) {
            if (!set.contains(s.charAt(right))) {
                set.add(s.charAt(right));
                maxLength = Math.max(maxLength, set.size());
                right++;
            } else {
                set.remove(s.charAt(left));
                left++;
            }
        }
        
        return maxLength;
    }
 }

No comments:

Post a Comment

| Designed by Colorlib