删除字符串中重现的字符c++实现
时间: 2023-06-14 13:07:05 浏览: 50
可以通过哈希表来实现。具体步骤如下:
1. 创建一个哈希表,用于记录字符串中出现过的字符。
2. 遍历字符串中的每个字符,如果字符在哈希表中不存在,则将该字符加入哈希表,并将其加入输出字符串中;否则不做任何操作。
3. 返回输出字符串。
下面是具体的 C++ 代码实现:
```cpp
#include <iostream>
#include <unordered_set>
#include <string>
using namespace std;
string removeDuplicates(string s) {
unordered_set<char> hash_table;
string result;
for (char c : s) {
if (!hash_table.count(c)) {
hash_table.insert(c);
result += c;
}
}
return result;
}
int main() {
string s = "hello world";
string result = removeDuplicates(s);
cout << result << endl; // 输出 "helo wrd"
return 0;
}
```
相关问题
删除字符串中某一字符c++
可以使用C++中的STL库中的erase和remove函数来删除字符串中的某一字符。
例如,以下代码可以删除字符串str中的所有字符'c':
```
#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string str = "Hello, world!";
str.erase(std::remove(str.begin(), str.end(), 'c'), str.end());
std::cout << str << std::endl;
return 0;
}
```
输出结果为:
```
Hello, worl!
```
删除字符串中重现的字符
可以使用一个哈希表记录每个字符出现的次数,然后再遍历一遍字符串,只将出现次数为1的字符加入结果字符串中,最终得到的结果就是删除重复字符后的字符串。
以下是Python的实现代码:
```python
def remove_duplicates(s):
freq = {}
for c in s:
freq[c] = freq.get(c, 0) + 1
res = ''
for c in s:
if freq[c] == 1:
res += c
return res
```
例如,对于字符串 "hello world",调用 `remove_duplicates("hello world")`,会返回 "he wrld"。