พิจารณาว่าเรามีรายการสตริง (List of Strings) รายการนั้นมีสตริงซ้ำบ้าง เราต้องตรวจสอบว่าสตริงไหนเกิดขึ้นมากกว่าหนึ่งครั้ง สมมติรายการสตริงเป็น ["Hello", "Kite", "Hello", "C++", "Tom", "C++"]
ที่นี่เราจะใช้เทคนิคแฮชชิง (Hashing) สร้างตารางแฮชว่าง แล้วท่องสตริงแต่ละตัว และสำหรับแต่ละสตริง s ถ้ามีอยู่ในแฮชแล้ว ให้แสดงสตริง มิฉะนั้น ใส่ลงในแฮช
ตัวอย่างโค้ด
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
void displayDupliateStrings(vector<string> strings) {
unordered_set<string> s;
bool hasDuplicate = false;
for (int i = 0; i < strings.size(); i++) {
if (s.find(strings[i]) != s.end()) {
cout << strings[i] << endl;
hasDuplicate = true;
} else
s.insert(strings[i]);
}
if (!hasDuplicate)
cout << "No Duplicate string has found" << endl;
}
int main() {
vector<string> strings{"Hello", "Kite", "Hello", "C++", "Tom", "C++"};
displayDupliateStrings(strings);
}
ผลลัพธ์
Hello C++