解題思路
先將樣本與目標統一為小寫。
逐字掃描,每次命中目標,若已有前次位置就輸出目前索引減前次索引,再更新前次位置。
這樣恰好計算每對相鄰出現的距離,且距離不受使用0或1起算索引影響。
時間 O(L),空間 O(L)字串與結果。
Step-by-step animation
教學小例:只記錄上一次命中位置
步驟 1 / 3
樣本aBAba、目標A
命中位置0
命中位置0
- 步驟
- 1
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
char t;
cin >> s >> t;
t = tolower(t);
int last = -1;
bool first = true;
for (int i = 0; i < (int)s.size(); i++)
if (tolower(s[i]) == t) {
if (last >= 0) {
if (!first)
cout << ' ';
first = false;
cout << i - last;
}
last = i;
}
cout << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。