엔지니어 게시판
LeetCode 솔루션 분류

[Easy - wk6 - Q1] 125. Valid Palindrome

컨텐츠 정보

본문

125. Valid Palindrome 


A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.

Given a string s, return true if it is a palindrome, or false otherwise.

 

Example 1:

Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.

Example 2:

Input: s = "race a car"
Output: false
Explanation: "raceacar" is not a palindrome.

Example 3:

Input: s = " "
Output: true
Explanation: s is an empty string "" after removing non-alphanumeric characters.
Since an empty string reads the same forward and backward, it is a palindrome.

 

Constraints:

  • 1 <= s.length <= 2 * 105
  • s consists only of printable ASCII characters.

관련자료

댓글 3

namsoo님의 댓글

  • 익명
  • 작성일
class Solution:
    def isPalindrome(self, s: str) -> bool:
       
        s2 = [x.lower() for x in s if x.isalpha() or x.isnumeric()]
        left = 0
        right = len(s2) - 1
       
        while left < right:
            if s2[left] != s2[right]:
                return False
            left += 1
            right -= 1
           
        return True

Coffee님의 댓글

  • 익명
  • 작성일
class Solution {
    
    public boolean isPalindrome(String s) {
        // two pointer
        for(int i=0, j=s.length()-1; i<j; i++, j--){
            while(i<j && !Character.isLetterOrDigit(s.charAt(i))){
                i++;
            }
            while(i<j && !Character.isLetterOrDigit(s.charAt(j))){
                j--;
            }
            
            if(Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(j))){
                return false;
            }
        }
        
        return true;
    }
    
    
}

학부유학생님의 댓글

  • 익명
  • 작성일
Runtime: 93 ms, faster than 19.64% of Python3 online submissions for Valid Palindrome.
Memory Usage: 14.7 MB, less than 43.06% of Python3 online submissions for Valid Palindrome.
class Solution:
    def isPalindrome(self, s: str) -> bool:
        new_s = ""
        for char in s:
            if ord('a') <= ord(char.lower()) <=ord('z'): new_s += char.lower()
            elif char.isdigit(): new_s += char
        return new_s[::-1] == new_s
전체 24 / 1 페이지
번호
제목
이름

최근글


인기글


새댓글


Stats


  • 현재 접속자 554 명
  • 오늘 방문자 2,962 명
  • 어제 방문자 7,414 명
  • 최대 방문자 14,831 명
  • 전체 회원수 1,543 명
알림 0