題目連結: https://tioj.ck.tp.edu.tw/problems/1010

# 內容

我們說字串 A 是字串 B 的 Prefix (前綴字串),若且唯若字串 B 的前 len (A) 個字母與 A 完全相同,其中 len (A) 指的是字串 A 的長度。例如: “Exam” 和 “Example” 都是 “Example” 的 Prefix,但是 “Ample” 和 “Exapple” 都不是 “Example” 的 Prefix。同樣的,當 B 的後 A 個字母與 完全相同的時候,我們稱 A 是 B 的 Suffix (後綴字串)。給定兩個字串 P、Q ,請你找出最長的字串 S 使得 S 是 P 的 Prefix,同時也是 Q 的 Suffix。請輸出 S 的最長長度

# 思路

因為是求 P 字串的前綴、Q 字串的後綴,所以,一開始就假設 len 為 min (P,Q),在比較 len 相同時 P、Q 的子字串是否相同,否則扣一,直到找到答案。
(c++ 有內建 substr)

# 程式碼

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main() {
    string P, Q;
    cin >> P >> Q;
    int ans = min(P.size(), Q.size());
    while (ans > 0 && (P.substr(0, ans) != Q.substr(Q.size()-ans)))
        --ans;
    cout << ans << endl;
    return 0;
}
更新於 閱讀次數

用實際行動犒賞爆肝的我😀

Zrn Ye LinePay

LinePay