Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Tìm ký tự lặp lại đầu tiên trong chuỗi trong C++


Cho chuỗi, tìm ký tự lặp lại đầu tiên. Ví dụ "Hello Friends" → 'l' (hai l liên tiếp).

Dùng bảng băm (unordered_set): duyệt chuỗi, nếu ký tự đã có trong tập hợp thì trả về, ngược lại thêm vào.

Ví dụ

#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); }

Kết quả

First repeating character is: l