【題解】ZeroJudge e837: P4. 字母排列 (Letters)

【題目敘述】https://zerojudge.tw/ShowProblem?problemid=e837
TOI 新手同好會 歷屆考題

#include <iostream>
using namespace std;

int cnt, ans, pos;
string s;

int main() {
    cin >> s;
    cnt = 1;
    ans = 1;
    for (int i = 1; i < s.length(); i++){
        if (s[i]-1 == s[i-1]) cnt++;
        else cnt = 1;
        if (cnt >= ans){
            ans = cnt;
            pos = i-cnt+1;
        }
    }
    cout << ans << " ";
    cout << s.substr(pos, ans) << "\n";
}

Python code (credit: Amy Chou)

s = input()
N = len(s)
idx = 0 #最長子字串的長度的起始位置
mx = 1 #最長子字串的長度
cnt = 1 #最後一個子字串的長度
for i in range(1, N):
    if ord(s[i]) == ord(s[i-1]) + 1:
        cnt += 1
    else:
        if cnt >= mx:
            mx = cnt
            idx = i - cnt
        cnt = 1

if cnt >= mx:
    mx = cnt
    idx = N - cnt

print(f"{mx} ", end="")
for i in range(idx, idx+mx):
    print(s[i], end="")

分享本文 Share with friends