본문 바로가기
<개인공부> - IT/[Python]

Regular expression practice

by Aggies '19 2019. 1. 17.
반응형

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

Note: For the purpose of this problem, we define empty string as valid palindrome.

Example 1:

Input: "A man, a plan, a canal: Panama"
Output: true

Example 2:

Input: "race a car"
Output: false


I know the concept of regular expression, however, I barely use this concept when I develop. I think I need more practice using regular expression so I brought this question from Leetcode.


import re

class Solution:

    def isPalindrome(self, s):

        """

        :type s: str

        :rtype: bool

        """

        

        s = re.sub(r'[^\w]','',s)

        s = s.lower()

        

        return s == s[::-1]

        

* re.sub(patternreplstringcount=0flags=0)

* r'[^\w]': [ ] -> Used to indicate a set of characters / \w -> For Unicode (str) patterns:



reference site : https://leetcode.com/explore/interview/card/top-interview-questions-easy/127/strings/883/discuss/219018/Fast-Python-Regular-Expression(Cheated...)

https://docs.python.org/3.2/library/re.html

반응형