給定字串陣列,移除重複項並保留原始輸入順序。C 標準庫無現成 Set/Map,需自行實作。
struct Item {
const char *sort_key; // 排序鍵值
const char *orig_str; // 原始字串
int orig_idx; // 原始順序
int tag; // 1=保留, 0=刪除
struct Item *self; // 指向原始陣列元素
};
int cmp(void *a, void *b) {
Item *x = (Item*)a, *y = (Item*)b;
int r = strcmp(x->sort_key, y->sort_key);
if (r == 0) y->self->tag = 0; // 標記重複
return r;
}
void swap(void *a, void *b) { /* 交換 sort_key 與 self 指標 */ }
// 排序後遍歷原始陣列,tag==1 者輸出
struct Node {
const char *str;
int tag; // 1=唯一, 0=重複
Node *left, *right;
};
Node* insert(Node *root, const char *s, int *tag_ptr) {
if (!root) {
root = malloc(sizeof(Node));
root->str = s; root->tag = 1; root->left = root->right = NULL;
*tag_ptr = 1;
} else {
int cmp = strcmp(s, root->str);
if (cmp == 0) { *tag_ptr = 0; } // 重複
else if (cmp < 0) root->left = insert(root->left, s, tag_ptr);
else root->right = insert(root->right, s, tag_ptr);
}
return root;
}
// 主程式:對每個輸入字串呼叫 insert,tag 回傳是否重複
| 方法 | 時間複雜度 | 空間複雜度 | 備註 |
|---|---|---|---|
| 排序法 | O(n log n) | O(n) | 簡單、穩定、需額外陣列 |
| BST 法 | 平均 O(n log n),最差 O(n²) | O(n) | 動態插入、可線上處理 |
| 雜湊表 | O(n) 平均 | O(n) | 工程首選,C 需自行實作或用第三方庫 |
std::unordered_set、Glib GHashTable、CCAN htable 等)。