본문 바로가기
파이썬 코딩테스트/해커랭크

HackerRank / Palindrome Index / Python

by S.T.Lee 2021. 12. 30.

https://www.hackerrank.com/challenges/palindrome-index/problem?isFullScreen=true

 

Palindrome Index | HackerRank

Determine which character(s) must be removed to make a string a palindrome.

www.hackerrank.com

 

들어가기 앞서

인덱스에서 ~의 역할을 알아볼건데

~는 비트연산자로 not의 의미를 가지고 있다.

이를 인덱스에 적용을하면 자신의 거울 위치에 해당되는 숫자가 되는것이다.

하단 참조.

https://blog.finxter.com/tilde-python/

 

Tilde (~) Operator in Python – Finxter

What is the Tilde ~ in Python? Python’s Tilde ~n operator is the bitwise negation operator: it takes the number n as binary number and “flips” all bits 0 to 1 and 1 to 0 to obtain the complement binary number. For example, the tilde operation ~1 beco

blog.finxter.com

while문 활용

def palindromeIndex(s):
    left=0
    while left<=len(s)//2:
        right = len(s) - left - 1
        if s[left] != s[~left]:
            if s[left+1:right+1] == s[right:left:-1]:
                return left
            elif s[left:right] == s[left:right][::-1]: #[right-1:left-1:-1]도 같은 의미지만 이렇게 할시 left=0일때 -1인덱스가 되므로 식이 성립하지 않는다.
                return right
            else:
                return -1
        left+=1
    return -1

 

for문 활용

def palindromeIndex(s):
    # Write your code here
    for ss in range(len(s)//2):
        left = ss
        right = len(s) - left - 1
        if s[ss] != s[~ss]:
            if s[left+1:right+1] == s[right:left:-1]:
                return left
            elif s[left:right] == s[left:right][::-1]:
                return right
    return -1