使用 C++ 找出字串中的第一個重複字元。
假設我們有一個字串;我們必須找到第一個重複的字元。因此,如果字串是“Hello Friends”,則第一個重複的字元將是 l。因為一個 l 在另一個 l 之後。
為了解決此問題,我們將使用雜湊技術。建立一個散列表,逐個掃描每個字元,如果字元不存在,則將其插入散列表,如果它已經存在,則返回該字元。
示例
#include<iostream> #include<unordered_set> using namespace std; char getFirstRepeatingChar(string &s) { unordered_set<char> hash; for (int i=0; i<s.length(); i++) { char c = s[i]; if (hash.find(c) != hash.end()) return c; else hash.insert(c); } return '\0'; } int main () { string str = "Hello Friends"; cout << "First repeating character is: " << getFirstRepeatingChar(str); }
輸出
First repeating character is: l
廣告