saurus2
Saurus2
saurus2
전체 방문자
오늘
어제
  • 분류 전체보기
    • 개발
      • AJAX
    • ML Ops
    • Profile
    • 음식점
    • 배낭여행
    • 컴퓨터공학
      • 알고리즘 공부
      • C++
      • Sever 스터디
      • Java spring
      • 알고리즘 _ 문제해결
      • 딥러닝
      • Java 정리
      • Python
      • LeetCode 1000
      • Machine Learning Study
      • Sign language Detection Pro..
      • LeetCode Solutions
    • 비콘
    • 데일리 리포트
    • 유학일기
      • 영어 공부
      • Daily
    • AI Master Degree
      • Data Mining
      • AI and Data engineering
      • Math Foundations for Decisi..
      • Natural Language Processing

블로그 메뉴

  • 홈
  • 태그
  • 미디어로그
  • 위치로그
  • 방명록

공지사항

인기 글

태그

  • 온라인저지
  • 백준
  • 릿코드
  • 알고리즘문제해결
  • DFS
  • LeetCode
  • two pointer
  • 개발자 취업준비
  • Python
  • 파이썬
  • 취준
  • 개발자
  • c++
  • 문제해결능력
  • 딥러닝
  • BFS
  • 취업준비
  • 리트코드
  • 딕셔너리
  • 알고리즘

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
saurus2

Saurus2

컴퓨터공학/LeetCode 1000

[LeetCode] 159. Longest Substring with At Most Two Distinct Characters

2022. 9. 24. 02:53

159. Longest Substring with At Most Two Distinct Characters

Medium

Given a string s, return the length of the longest substring that contains at most two distinct characters.

 

Example 1:

Input: s = "eceba"
Output: 3
Explanation: The substring is "ece" which its length is 3.

Example 2:

Input: s = "ccaabbb"
Output: 5
Explanation: The substring is "aabbb" which its length is 5.

 

Constraints:

  • 1 <= s.length <= 10^5
  • s consists of English letters.

문제 풀이

  • 가장긴 부분 문자열을 찾아야한다. 
  • 연결된 가장긴 문자열에는 알파벳이 두개만 존재해야한다.
  • 딕셔너리(해쉬테이블, DAT) 를 사용해서 기록하고, 
  • 이를 이용하여 슬라이딩 윈도우(투포인터)로 문제를 푼다.
  • 두번째 포인터를 계속 옮기면서 딕셔너리에 갯수를 세어준다.
  • 만약 딕셔너리에 있는 알파벳 갯수가 2를 넘으면, 해당 위치의 딕셔너리 갯수를 줄여준다.
  • 알파벳의 개수가 0이면 딕셔너리에서 제거해줘야 전체 갯수를 셀때 편리하다.
  • 추가적으로, 답을 구할때 알파벳의 갯수가 2를 넘지 않을때만 최대값을 계산해줘야한다. 

소스 코드

class Solution:
    def lengthOfLongestSubstringTwoDistinct(self, s: str) -> int:
        cnt = defaultdict(int)
        p1, p2, res = 0, 0, 0
        while p2 < len(s):
            cnt[s[p2]] += 1
            if len(cnt) > 2:
                cnt[s[p1]] -= 1
                if cnt[s[p1]] == 0:
                    del(cnt[s[p1]]) 
                p1 += 1
            else:
                res = max(res, sum(cnt.values()))
            p2 += 1
        return res
저작자표시 (새창열림)

'컴퓨터공학 > LeetCode 1000' 카테고리의 다른 글

[LeetCode] 298. Binary Tree Longest Consecutive Sequence  (0) 2022.09.27
[LeetCode] 990. Satisfiability of Equality Equations  (0) 2022.09.26
[LeetCode] 1680. Concatenation of Consecutive Binary Numbers  (0) 2022.09.24
[LeetCode] 1272. Remove Interval  (1) 2022.09.23
[LeetCode] 557. Reverse Words in a String III  (1) 2022.09.23
    '컴퓨터공학/LeetCode 1000' 카테고리의 다른 글
    • [LeetCode] 298. Binary Tree Longest Consecutive Sequence
    • [LeetCode] 990. Satisfiability of Equality Equations
    • [LeetCode] 1680. Concatenation of Consecutive Binary Numbers
    • [LeetCode] 1272. Remove Interval
    saurus2
    saurus2
    Simple is Best

    티스토리툴바