Problem
- Find the length of the longest substring in the given string that is the same in reverse.
- 주어진 문자열에서 거꾸로 해도 동일한 가장 긴 문자열의 길이를 찾는다.
- If the length of the input string is 0, the return value must be 0.
Palindrome
: 회문 (앞에서부터 읽으나 뒤에서부터 읽으나 동일한 단어나 구)
Solution 01
function longestPalindrome(str) {
if (str === '') return 0;
for (let i = str.length; i >= 0; i--) {
for (let j = 0; j <= str.length - 1; j++) {
if (str.substr(j, i) === str.substr(j, i).split('').reverse().join('')) {
return i;
}
}
}
}
longestPalindrome(''); // 0
longestPalindrome('a'); // 1
longestPalindrome('app'); // 2
longestPalindrome('racecar'); // 7
longestPalindrome('madam'); // 5
longestPalindrome('baabcd'); // 4
Solution 02
function longestPalindrome(str) {
let isPalindrome = str => str === str.split('').reverse().join('');
for (let i = str.length; i >= 0; i--) {
for (let j = str.length - i; j >= 0; j--) {
if (isPalindrome(str.substr(j, i))) {
return i;
}
}
}
}
longestPalindrome(''); // 0
longestPalindrome('a'); // 1
longestPalindrome('app'); // 2
longestPalindrome('racecar'); // 7
longestPalindrome('madam'); // 5
longestPalindrome('baabcd'); // 4
Solution 03
function longestPalindrome(str) {
let isPalindrome = str => str === str.split('').reverse().join('');
let longest = 0;
for (let i = 0; i < str.length; i++) {
for (let j = i + 1; j <= str.length; j++) {
if (isPalindrome(str.slice(i, j)) && longest < str.slice(i, j).length) {
longest = str.slice(i, j).length;
}
}
}
return longest;
}
longestPalindrome(''); // 0
longestPalindrome('a'); // 1
longestPalindrome('app'); // 2
longestPalindrome('racecar'); // 7
longestPalindrome('madam'); // 5
longestPalindrome('baabcd'); // 4