給定字符串,找出第一個只出現一次的字符。例如 "1222345678234543" → '1'(索引 0)。
利用固定大小數組(ASCII 256 或 128)記錄每個字符的:
1. 首次出現索引
2. 出現次數
struct Info { int idx = -1; int cnt = 0; };
Info stat[256]; // 覆蓋擴展 ASCII
for (int i = 0; i < len; ++i) {
unsigned char c = str[i];
if (stat[c].idx == -1) stat[c].idx = i; // 僅記錄首次
stat[c].cnt++;
}
int ansIdx = INT_MAX;
for (int i = 0; i < 256; ++i)
if (stat[i].cnt == 1)
ansIdx = min(ansIdx, stat[i].idx);
char ans = (ansIdx == INT_MAX) ? '\0' : str[ansIdx];
O(n + Σ),Σ=256 為字符集大小,視為常數 → O(n)。O(Σ) → O(1) 額外空間。c - 'a' 映射。unordered_map,空間變為 O(k)(k 為不同字符數)。
#include
#include
#include
using namespace std;
char firstUnique(const char* s) {
struct Node { int idx = -1, cnt = 0; } map[256];
int len = strlen(s);
for (int i = 0; i < len; ++i) {
unsigned char c = s[i];
if (map[c].idx == -1) map[c].idx = i;
map[c].cnt++;
}
int best = INT_MAX;
for (int i = 0; i < 256; ++i)
if (map[i].cnt == 1) best = min(best, map[i].idx);
return (best == INT_MAX) ? '\0' : s[best];
}
int main() {
cout << firstUnique("1222345678234543") << endl; // 輸出 1
return 0;
}