Cho chuỗi s. Loại bỏ các ký tự trùng lặp liên tiếp, chỉ giữ 1 ký tự.
Ví dụ: "heeeeelllllllloooooo" → "helo".
Thuật toán
- Duyệt chuỗi, giữ ký tự nếu khác ký tự cuối của kết quả.
Ví dụ triển khai (C++)
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
string solve(string s) {
string ret = "";
for (char c : s) {
if (!ret.empty() && ret.back() == c) continue;
ret += c;
}
return ret;
}
};
int main() {
Solution ob;
cout << ob.solve("heeeeelllllllloooooo");
return 0;
}
Đầu ra
helo