Palindrome이란 앞뒤로 뒤집어도 같은 문자열을 Palindrome이라고 한다.
Palindrome인지 판별하는 함수
function isPalin(s) { const mid = Math.floor(s.length / 2); for(let i = 0; i < mid; i++) { if(s[i] !== s[s.length -1 - i]) { return false; } } return true; }
일단 문자열의 중간을 구한 뒤 중간을 기준으로 첫글자와 마지막 글자를 비교해
한번이라도 일치하지 않으면 false를 반환한다.
function isPalin(s) { for(let i = 0; i < s.length; i++) { s = s.toLowerCase().replace(/a-z/g, ''); if(s.split('').reverse() !== s) { return false; } return true; }
특수문자나 숫자 등을 제외한 뒤 판별하는 함수이다.
let longestPalindrome = function (str) { // TODO: 여기에 코드를 작성합니다. if(str.length <= 1) return str.length; for(let i = str.length; i > 0; i--) { for(let j = 0; j <= str.length -i; j++) { const isPal = isPalin(str.slice(j, i + j)) if(isPal) return i } } function isPalin(s) { const mid = Math.floor(s.length / 2); for(let i = 0; i < mid; i++) { if(s[i] !== s[s.length -1 - i]) { return false; } } return true; } };
함수에 'My dad is a racecar athlete'를 대입해 콘솔 찍어 보면...
There is a tattarrattat
There is a tattarratta
here is a tattarrattat
There is a tattarratt
here is a tattarratta
ere is a tattarrattat
There is a tattarrat
here is a tattarratt
ere is a tattarratta
re is a tattarrattat
There is a tattarra
here is a tattarrat
ere is a tattarratt
re is a tattarratta
e is a tattarrattat
There is a tattarr
here is a tattarra
ere is a tattarrat
re is a tattarratt
e is a tattarratta
is a tattarrattat
There is a tattar
here is a tattarr
ere is a tattarra
re is a tattarrat
e is a tattarratt
is a tattarratta
is a tattarrattat
There is a tatta
here is a tattar
ere is a tattarr
re is a tattarra
e is a tattarrat
is a tattarratt
is a tattarratta
s a tattarrattat
There is a tatt
here is a tatta
ere is a tattar
re is a tattarr
e is a tattarra
is a tattarrat
is a tattarratt
s a tattarratta
a tattarrattat
There is a tat
here is a tatt
ere is a tatta
re is a tattar
e is a tattarr
is a tattarra
is a tattarrat
s a tattarratt
a tattarratta
a tattarrattat
There is a ta
here is a tat
ere is a tatt
re is a tatta
e is a tattar
is a tattarr
is a tattarra
s a tattarrat
a tattarratt
a tattarratta
tattarrattat
There is a t
here is a ta
ere is a tat
re is a tatt
e is a tatta
is a tattar
is a tattarr
s a tattarra
a tattarrat
a tattarratt
tattarratta
tattarrattat
요렇게 나온다...정말 대단한 것 같다..