[LeetCode]Valid Palindrome

2024. 4. 9. 21:50·SW개발/코딩테스트

https://leetcode.com/problems/valid-palindrome/description/

 

LeetCode - The World's Leading Online Programming Learning Platform

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

 

문제 분석

주어진 문자열이 유효한 Palindrome인지 구하는 문제입니다.

 

처음 시도한 답안

class Solution:
    def isPalindrome(self, s: str) -> bool:
        s = s.lower()

        left = 0
        right = len(s) - 1
        while left < right:
            while not s[left].isalnum() and left < right:
                left += 1
            
            while not s[right].isalnum() and left < right:
                right -= 1

            if s[left] != s[right]:
                return False

            left += 1
            right -= 1

        return True

접근 방법

  1. 먼저 문자열을 모두 소문자로 변경합니다.
  2. 가장 왼쪽에서 시작하는 left, 오른쪽에서 시작하는 right 변수를 선언합니다.
  3. left 포인터가 right보다 커지기 전까지 반복합니다.
    1. 등장한 문자가 숫자거나 알파벳이 될때까지 left를 오른쪽으로 1칸 움직입니다. (숫자나 알파벳 이외엔 모두 무시, 공백등)
    2. 마찬가지로 오른쪽 포인터도 숫자이거나 알파벳이 나올때까지 right를 왼쪽으로 1칸 움직입니다.
    3. 만약 등장한 두 문자가 다르다면 Palindrome이 아닙니다.
    4. 등장한 문자가 같다면 left+1, right-1 하여 포인터를 움직입니다.

Palindrome을 검사하는 방법으로 왼쪽, 오른쪽 투 포인터 방식을 사용합니다. 각 포인터를 하나씩 옮기면서 등장한 문자가 같은지 비교하는 방법입니다.

 

728x90

'SW개발 > 코딩테스트' 카테고리의 다른 글

[LeetCode]Count Sub Islands  (0) 2024.04.11
[LeetCode]Max Area of Island  (0) 2024.04.10
[LeetCode]Course Schedule  (0) 2024.04.08
[LeetCode]Number of Islands  (0) 2024.04.07
[LeetCode]Clumsy Factorial  (0) 2024.04.06
'SW개발/코딩테스트' 카테고리의 다른 글
  • [LeetCode]Count Sub Islands
  • [LeetCode]Max Area of Island
  • [LeetCode]Course Schedule
  • [LeetCode]Number of Islands
Leffe_pt
Leffe_pt
개발자로서 성장하면서 배워온 지식과 경험을 공유하는 공간입니다.
  • Leffe_pt
    Leffe's tistory
    Leffe_pt
  • 전체
    오늘
    어제
    • 분류 전체보기 (307)
      • SW개발 (303)
        • 코딩테스트 (172)
        • 개발이야기 (23)
        • IT 용어 (17)
        • Python (22)
        • Django (46)
        • Flask (2)
        • Database (1)
        • SQLAlchemy (0)
        • Javascript (5)
        • Linux, Unix (3)
        • JAVA (2)
        • Spring (10)
      • 회고 (4)
      • 사진 (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    음식
    오픈소스
    배공파용
    g
    트리 #AVL #알고리즘 #자료구조
    라이프 스타일
    어플리케이션
    배달비 공유
    배달
    Contributor
    컨트리뷰터
    django
    플레이스토어
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Leffe_pt
[LeetCode]Valid Palindrome
상단으로

티스토리툴바