1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

今回はPaizaの「回文判定」に挑戦!前回学んだreverse()が使えそう?!

🧪 問題概要
「文字列Sが回文かどうかを判定せよ」
回文とは「たけやぶやけた」みたいに、前から読んでも後ろから読んでも同じ文字列のこと。


入力例:

paizaazzap

出力例:

NO



💥 NGコード例

const firstHalf = text.slice(0, half);
const secondHalf = text.slice(half);
if(firstHalf === secondHalf.reverse()) {
  console.log("YES");
}

一見良さそうに見えるけど、reverse()で反転させただけで、ちゃんとjoin(”)しないと配列のまま比較されてしまうので要注意!



✅ OKコード例

const rl = require('readline').createInterface({input:process.stdin});

rl.once('line',(input)=>{
    const text = input.split('');
    
    if(text.length % 2 === 0){
        const half = Number(text.length / 2)
        const firstHalf = text.slice(0, half).join('');
        const secondHalf = text.slice(half);
        
        if(firstHalf === secondHalf.reverse().join('')){
            console.log("YES");
        }else{
            console.log("NO");
        }
    
        
    }
    
    else{
        const half = Math.floor(text.length / 2);
        const firstHalf = text.slice(0, half).join('');
        const secondHalf = text.slice(half+1);
        
        if(firstHalf === secondHalf.reverse().join('')){
            console.log("YES");
        }else{
            console.log("NO");
        }
    }
    
    
});

💡 解説

  • 回文とは「前半」と「後半を逆にしたもの」が等しい文字列のこと。
  • 奇数文字列では中央の1文字は無視(slice(half + 1))。
  • .slice(…).reverse().join'') を使って逆順の文字列を作成。


✅ 簡単な回文チェック方法

rl.once('line', (input) => {
    const reversed = input.split('').reverse().join('');
    console.log(input === reversed ? 'YES' : 'NO');
});

前から読んでも後ろから読んでも同じなんだから、
シンプルに「全部ひっくり返して比べる」が最速。

📝 メモまとめ

  • reverse() だけじゃ文字列比較できない、配列のままになる
  • join('') で文字列に戻してから比較が正解
  • 奇数長の文字列では中央1文字を無視(sliceで対応)
  • シンプルに全部ひっくり返して、元と比べるのがはやい。




僕の失敗談(´;ω;`)と解決法🐈

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?