far

[JS 알고리즘] 유효한 팰린드롬 본문

알고리즘/알고리즘 베이스

[JS 알고리즘] 유효한 팰린드롬

Eater 2023. 3. 25. 01:54

유효한 팰린드롬

앞에서 읽을 때나 뒤에서 읽을 때나 같은 문자열을 팰린드롬이라고 합니다. 문자열이 입력되면 해당 문자열이 팰린드롬이면 "YES", 아니면 “NO"를 출력하는 프로그램을 작성하세요.

단 회문을 검사할 때 알파벳만 가지고 회문을 검사하며, 대소문자를 구분하지 않습니다. 알파벳 이외의 문자들의 무시합니다.

 

입력설명
첫 줄에 정수 길이 100을 넘지 않는 공백이 없는 문자열이 주어집니다. 

 

출력설명
첫 번째 줄에 팰린드롬인지의 결과를 YES 또는 NO로 출력합니다.

 

입력예제
found7, time: study; Yduts; emit, 7Dnuof

 

출력예제
YES

 

// 나의 풀이

function solution(s){
    let answer = "YES";
    const drome = s.toLowerCase().replace(/[^a-z]/g, '').split('')
    for(let i = 0; i < Math.floor(drome.length/2); i++) {
        if(drome[i] !== drome[drome.length - 1 - i]) {
            answer = "NO"
        }
    }
    return answer;
}

let str="found7, time: study; Yduts; emit, 7Dnuof";
console.log(solution(str));

정규 표현식으로 알파벳 이외의 문자를 제거하고 이전 문제에서 배운 Math.floor와 나누기를 사용해 for문을 줄이는 방식을 써봤다.

// 강의의 풀이

function solution(s){
    let answer="YES";
    s=s.toLowerCase().replace(/[^a-z]/g, '');
    if(s.split('').reverse().join('')!==s) return "NO";
    return answer;
}

let str="found7, time: study; Yduts; emit, 7Dnuof";
console.log(solution(str));

reverse를 사용해 비교한 풀이. 팰린드롬은 reverse를 적극 활용하는 편이 좋을 것 같다.

Comments