b468簡單

重複字母間距

運用每字母最近一次出現位置,正確求解本題並處理邊界情況。

解題思路

掃描每個字元,若先前出現過,就以目前位置減最近位置更新最小差,再更新最近位置。

同字母若考慮更早的位置,距離只會更大,所以只需最近一次。

未曾找到重複時輸出-1。

時間 O(|S|),字串 O(|S|),額外 O(26)。

Step-by-step animation

教學例子:教學字串 abac,讀到 a、b。

回報動畫錯誤
步驟 1 / 3

步驟 1

教學字串 abac,讀到 a、b。

a
b
狀態
尚無重複

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    string s;
    cin >> s;
    int last[26];
    fill(last, last + 26, -1);
    int ans = INT_MAX;
    for (int i = 0; i < (int)s.size(); i++) {
        int c = s[i] - 'a';
        if (last[c] >= 0)
            ans = min(ans, i - last[c]);
        last[c] = i;
    }
    cout << (ans == INT_MAX ? -1 : ans) << '\n';
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多