[Python] 125. Valid Palindrome

2021. 1. 8. 18:09·study/LeetCode
728x90

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

 

Valid Palindrome - 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

풀이

from collections import deque

class Solution:
    def isPalindrome(self, s: str) -> bool:
        # 소문자로 만들기
        s = s.lower()
        # 문자를 넣을 deque
        strings = deque()
        
        # 소문자로 통일한 문장에서 영어, 한글만 strings 덱에 추가
        for i in s:
            if i.isalnum() is True:
                strings.append(i)
        # 덱의 제일 앞과 뒤가 같은지 비교
        while len(strings) > 1: # 제일 앞과 뒤를 비교할 것이기 때문에 한개가 남으면 빠져나감
            if strings.popleft() != strings.pop():
                return False
        return True

팰린드롬

앞뒤가 똑같은 단어나 문장으로, 뒤집어도 같은말이 되는 단어

1. 공백제거
2. 알파벳 대소문자 통일
3. 비교

 

isalnum()

문자열이 영어, 한글 혹은 숫자로 되어 있으면 True 리턴

그렇지 않다면 False 리턴

print("python101".isalnum())

#True

 

lower()

소문자로 바꾼다.

* upper() : lower와 반대되는 함수

* islower() : 소문자인지 확인하는 함수

print("abcd".islower())

#True

시간을 단축시키기 위해

1.  리스트 말고 덱 이용하기

   리스트의 pop(0)는 O(n)인데 반해, 덱의 popleft()는 O(1)의 속도를 가짐.

   이를 n번씩 반복하면 리스트 구현은 O(n^2) 인데 반해, 덱의 구현은 O(n)로 성능차이가 큼.

2. 슬라이싱 이용하기

3. 처음에 모든 문자를 소문자로 바꾸는 것이 아닌 문자만 소문자로 바꾸도록 하기

4. len>= 2 보다 len > 1 사용하기


처음 생각했던 알고리즘의 문제점(틀린 이유)

1. 문자를 사용자한테 입력을 받는다 생각해서 input 함수를 넣었음
2. 공백 제거를 생각을 못함.

3. 한번 쓰는거면 애초에 선언을 안하는 것이 좋을 수도 있음 ex) bool 변수

 

그나마 잘한점

1. 슬라이싱 이용하려 했던 점...

bool = True
print("문자", s)
length = int(len(s)/2)
text = s.strip()
text = text.lower()
print("문자", s)
for i in range(length):
    if(text[i] != text[-i]):
        bool = False
return bool

 

 

728x90

'study > LeetCode' 카테고리의 다른 글

[Python] 15. Two Sum  (0) 2021.02.17
[Python] 1. Two Sum  (0) 2021.01.22
[Python] 819. Most Common Word  (0) 2021.01.15
[Python] 937. Reorder Log Files  (0) 2021.01.15
[Python] 344. Reverse String  (0) 2021.01.08
'study/LeetCode' 카테고리의 다른 글
  • [Python] 1. Two Sum
  • [Python] 819. Most Common Word
  • [Python] 937. Reorder Log Files
  • [Python] 344. Reverse String
bbooo
bbooo
  • bbooo
    bbooo
    bbooo
  • 전체
    오늘
    어제
    • 분류 전체보기 (142)
      • study (61)
        • 백준(BOJ) (34)
        • Programmers (15)
        • LeetCode (9)
      • AI (4)
        • Paper (0)
      • SSAC X IFFEL (4)
        • DeepML (1)
        • 밑바닥 부터 시작하는 딥러닝 (2)
      • 회고 (46)
      • Error (10)
      • Setting (15)
  • 블로그 메뉴

    • 홈
    • 태그
    • 글쓰기
    • 관리
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    프로그래머스 석유시추
    파이썬
    set
    백준 2470
    docker
    풀이 실패
    파이썬 석유시추
    LeetCode
    그리디 알고리즘
    문자열을 원하는 길이로
    코딩테스트 준비
    sequence item 0: expected str instance int found
    개발자 취업
    Counter
    python 과제 진행하기
    두 포인터
    백준
    python 석유시추
    브루트포스
    programmers 석유시추
    vscode
    sort
    항해99
    99클럽
    typeerror: sequence item 0: expected str instance int found
    백트래킹
    programmers 과제 진행하기
    파이썬 과제 진행하기
    Til
    투포인터
  • 최근 댓글

  • hELLO· Designed By정상우.v4.10.3
bbooo
[Python] 125. Valid Palindrome
상단으로

티스토리툴바