본문 바로가기
코딩테스트(알고리즘)/leetCode

[leetCode] 125. Valid Palindrome (Javascript)

by Cafe Mocha 2022. 6. 25.

(5) Valid Palindrome - LeetCode

 

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


접근 : 투포인터

1. 아스키코드를 통한 필터링

2. 앞 뒤 포인터로 값 비교

 

javascript

let input = require("fs")
  .readFileSync("input.txt") //"/dev/stdin"
  .toString()
  .split("\n")
  .map((val) => val.trim());

function solution(input) {
  //input
  let s = input[0];

  //Submit
  s = s
    .split("")
    .map((v) => v.toLowerCase())
    .join("");
  let arr = [];

  for (let i = 0; i < s.length; i++) {
    let c = s.charCodeAt(i);
    if ((c >= 97 && c <= 122) || (c >= 48 && c <= 57)) arr.push(s[i]);
  }

  let left = 0;
  let right = arr.length - 1;
  let check = true;
  while (left < right) {
    if (left === right) break;

    if (arr[left] !== arr[right]) {
      check = false;
      break;
    }

    left++;
    right--;
  }

  console.log(check);
  return check;
}

solution(input);