Leetcode

[LeetCode Medium] 3. Longest Substring Without Repeating Characters [C/C++]

치킨먹고싶어요 2022. 5. 25. 17:40

https://leetcode.com/problems/longest-substring-without-repeating-characters/

 

Longest Substring Without Repeating Characters - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

해석 

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

String s에서 가장 긴 부분 연속 string의 길이를 알파벳의 중복없이 구하라는 내용입니다.

코드

슬라이딩 윈도우로 풀 수 있는 간단한 문제입니다.  

class Solution {
    string sub;
    int p, q, ans, tmp;
    bool alpabet[130];
public:
    int lengthOfLongestSubstring(string s) {
        this->= -1this-> q = 0this->ans = 0this->tmp = 0;
        while (q < s.length()) {
            if (alpabet[s[q]]) {
                alpabet[s[++p]] = false;
                tmp--;
            }
            else {
                alpabet[s[q++]] = true;
                ans = ans < ++tmp ? tmp : ans;
            }
        }
       return ans;
    }
};
 
cs

O(n)으로 푸니 98.51%의 코드보다 빠르다고 나옵니다.

아마도 map을 사용해서 푸는 사람이 많아서 그런가 봅니다.

알파벳 소문자만 인풋으로 주어지지 않는 다는 점만 주의해주면 쉬운 문제였습니다.