LeetCode 코딩 문제 2021/06/09 - Valid Palindrome

이호현·2021년 6월 9일
0

Algorithm

목록 보기
122/138

[문제]

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

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.

(요약) 공백이나 특수문자를 제외한 숫자나 알파벳이 palindrome인지 확인.(대, 소문자 구분 X)

[풀이]

var isPalindrome = function(s) {
  const reg = /[^A-Za-z0-9]/;
  const tempStr = s.split(reg).join('').toLowerCase();

  for(let i = 0, len = tempStr.length; i < Math.floor(len / 2); i++) {
    if(tempStr[i] !== tempStr[len - i - 1]) {
      return false;
    }
  }

  return true;
};

알파벳과 숫자가 아닌것을 확인하는 정규식을 만들어서 주어진 문자열을 split()으로 알파벳과 숫자만 남김.

그렇게 만들어진 배열을 합치고, 모두 소문자로 바꿈.

맨 앞과 맨 뒤에서 시작해 서로 비교해 가면서 같은 문자인지 아닌지 확인.

profile
평생 개발자로 살고싶습니다

0개의 댓글