반응형

3. Longest Substring Without Repeating Characters (Medium)

 

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

 

Example 1:

Input: "abcabcbb"

Output: 3

Explanation: The answer is "abc", with the length of 3.

 

Example 2:

Input: "bbbbb"

Output: 1

Explanation: The answer is "b", with the length of 1.

 

Example 3:

Input: "pwwkew"

Output: 3

Explanation: The answer is "wke", with the length of 3.

Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

 

 

Java Solution

import java.util.*;

class Solution {
    public int lengthOfLongestSubstring(String s) {
        Set set = new HashSet();
        int n = s.length();
        int begin = 0, end = 0;
        int ans = 0;

        while(end < n) {
            if(set.contains(s.charAt(end))) {
                set.remove(s.charAt(begin++));
            } else {
                set.add(s.charAt(end++));
                ans = Math.max(ans, end - begin);
            }
        }
        return ans;
    }
}

 

Kotlin Solution

class Solution {
    fun lengthOfLongestSubstring(s: String): Int {
        val set = hashSetOf<Char>()
        val n = s.length
        var begin = 0
        var end = 0
        var answer = 0

        while (end < n) {
            if (s[end] in set) {
                set.remove(s[begin++])
            } else {
                set.add(s[end++])
                answer = Integer.max(answer, end - begin)
            }
        }
        return answer
    }
}

 

이 외에도 다양한 문제들의 해답 코드를 깃헙 저장소에서 확인할 수 있습니다. (Java, Kotlin)


 

반응형
반응형