0
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?

「決まり字」を解くために : part3

Posted at

今回は paiza の「「決まり字」を解くために : part3」の問題に挑戦!


問題概要

  • 背景:決まり字を求めるには、まずは最長共通接頭辞を求める必要がある。

  • 2つの和歌の上の句を比べて、
    最初からどこまで同じ文字が続くか(=最長共通接頭辞:LCP) の「長さ」を求める。



入力例:

2
akinotanokarihonoionotomaoarami
akikazenitanabikukumonotaemayori

出力例:

3






✅ OK例:

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

const lines = [];

rl.on('line', (input) => lines.push(input));

rl.on('close', () => {
    const N = Number(lines[0]);
    const s = lines.slice(1);
    
    const a = s[0];
    const b = s[1];
    
    let count = 0;
    for (let i = 0; i < Math.min(a.length, b.length); i++) {
        if (a[i] === b[i]) {
            count++;
        } else {
            break;
        }
    }
    
    console.log(count);
});

🧩 コードの流れ

  • 入力を受け取る
  • カウント用変数を準備
  • 短い方の長さまでループ
  • 文字を比較
    • 同じなら count++
    • 違った瞬間に break(共通接頭辞が終わる)
  • 最終的に count を出力






🗒️ まとめ

  • 「最長共通接頭辞(LCP: Longest Common Prefix)」を求める問題

  • 共通接頭辞とは、文字列の先頭から順に一致する部分(例:「apple」と「april」の共通接頭辞は「ap」)

  • 処理内容:

    • 先頭から1文字ずつ比較し、違った時点でループ終了
    • for ループで s1[i] === s2[i] をチェックし、一致するたびに count++
    • 一致しなくなった瞬間に break(=共通接頭辞が終わる)
    • Math.min(a.length, b.length) で短い方の長さまで比較する




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

0
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
0
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?