Dev study and notes

리트코드 0003 중복되지 않는 가장 긴 부분 문자열 찾기 LEETCODE 3. Longest Substring Without Repeating Characters 본문

LEETCODE

리트코드 0003 중복되지 않는 가장 긴 부분 문자열 찾기 LEETCODE 3. Longest Substring Without Repeating Characters

devlunch4 2024. 12. 3. 17:59
반응형

3. 중복되지 않는 가장 긴 부분 문자열 찾기

3. Longest Substring Without Repeating Characters

영문 버전/ENGLISH Ver

Difficulty Topics Hints URL
Easy Hash_Table
String
Sliding_Window
1 https://leetcode.com/problems/longest-substring-without-repeating-characters/description/

 

Table of Contents

설명

문자열 s가 주어졌을 때, 중복된 문자가 없는 가장 긴 부분 문자열의 길이를 구하세요.

 

 

예제

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.

 

제약 사항:

  • 0 <= s.length <= 5 * 104
  • s는 영어 대소문자, 숫자, 기호 및 공백으로 이루어져 있습니다.

 

Solutions

JAVA

class Solution {
    public int lengthOfLongestSubstring(String s) {
          Set<Object> set = new HashSet<>();
        int strLength = s.length();
        int begin = 0;
        int end = 0;
        int res = 0;
        while (end < strLength) {
            if (set.contains(s.charAt(end))) {
                set.remove(s.charAt(begin++));
            } else {
                set.add(s.charAt(end++));
                res = Math.max(res, end - begin);
            }
        }
        return res;
    }
}
반응형
Comments