Palindrome


Palindrome


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;
}
特殊文字や数字などを除く判別関数.

部分の文字列の中で最も長いPalindromeを求めます

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パパis a Racecarアスリート」を代入してコンソールを撮ると...
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
このように出てきます...本当にすごい...