앞에서 읽을 때나 뒤에서 읽을 때나 같은 문자열을 팰린드롬이라고 합니다.
문자열이 입력되면 해당 문자열이 팰린드롬이면 "YES", 아니면 “NO"를 출력하는 프로그램을 작성하세요.
단 회문을 검사할 때 알파벳만 가지고 회문을 검사하며, 대소문자를 구분하지 않습니다. 알파벳 이외의 문자들의 무시합니다.
없음
첫 줄에 정수 길이 100을 넘지 않는 공백이 없는 문자열이 주어집니다.
첫 번째 줄에 팰린드롬인지의 결과를 YES 또는 NO로 출력합니다.
▣ 입력예제 1
▣ 출력예제 1
function solution(s) {
let answer = "YES";
let str = s.toLowerCase().replace(/[^a-z]/g, "");
if (str.split("").reverse().join("") !== str) answer = "NO";
return answer;
}
let str = "found7, time: study; Yduts; emit, 7Dnuof";
console.log(solution(str));
function solution(s) {
// 0. 반환해야 하는 answer의 초기값은 "YES"로 할당한다.
let answer = "YES";
// 1.1 인자로 받아온 문자열을 소문자로 통일시키고,
// 1.2 인자로 받아온 문자열에서 소문자 알파벳만 남기는 정규식을 사용해서 빈 문자열로 변환해버린다.
let str = s.toLowerCase().replace(/[^a-z]/g, ""); // foundtimestudyydutsemitdnuof
// 2. 만약 str을 뒤집은 결과가 str과 같지 않다면 "NO"를 반환하도록 한다.
if (str.split("").reverse().join("") !== str) answer = "NO";
// 3. answer의 결과를 최종적으로 반환한다.
return answer;
}
let str = "found7, time: study; Yduts; emit, 7Dnuof";
console.log(solution(str)); // YES
toLowerCase()
메서드toLowerCase()
메서드는 문자열을 소문자로 변환해 반환합니다.Example
const sentence = 'The quick brown fox jumps over the lazy dog.';
console.log(sentence.toLowerCase());
// expected output: "the quick brown fox jumps over the lazy dog."
replace()
메서드replace()
메서드는 어떤 패턴에 일치하는 일부 또는 모든 부분이 교체된 새로운 문자열을 반환합니다. 그 패턴은 문자열이나 정규식(RegExp)이 될 수 있으며, 교체 문자열은 문자열이나 모든 매치에 대해서 호출된 함수일 수 있습니다.Example
const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
console.log(p.replace('dog', 'monkey'));
// expected output: "The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?"
const regex = /Dog/i;
console.log(p.replace(regex, 'ferret'));
// expected output: "The quick brown fox jumps over the lazy ferret. If the dog reacted, was it really lazy?"
split()
메서드split()
메서드는 String 객체를 지정한 구분자를 이용하여 여러 개의 문자열로 나눕니다.Example
const chars = str.split('');
console.log(chars[8]);
// expected output: "k"
const strCopy = str.split();
console.log(strCopy);
// expected output: Array ["The quick brown fox jumps over the lazy dog."]
reverse()
메서드reverse()
메서드는 배열의 순서를 반전합니다. 첫 번째 요소는 마지막 요소가 되며 마지막 요소는 첫 번째 요소가 됩니다.Example
const array1 = ['one', 'two', 'three'];
console.log('array1:', array1);
// expected output: "array1:" Array ["one", "two", "three"]
const reversed = array1.reverse();
console.log('reversed:', reversed);
// expected output: "reversed:" Array ["three", "two", "one"]
// Careful: reverse is destructive -- it changes the original array.
console.log('array1:', array1);
// expected output: "array1:" Array ["three", "two", "one"]
join()
메서드join()
메서드는 배열의 모든 요소를 연결해 하나의 문자열로 만듭니다.