用c++实现给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。输入: 示例: leetcode loveleetcode 输出: 0 2 提示:你可以假定该字符串只包含小写字母。
时间: 2024-02-05 08:13:24 浏览: 131
以下是C++的实现代码:
```c++
#include <iostream>
#include <unordered_map>
using namespace std;
int firstUniqChar(string s) {
unordered_map<char, int> freq;
// 统计每个字符出现的频率
for (char c : s) {
freq[c]++;
}
// 找到第一个出现次数为1的字符
for (int i = 0; i < s.size(); i++) {
if (freq[s[i]] == 1) {
return i;
}
}
return -1;
}
int main() {
string s = "leetcode";
cout << firstUniqChar(s) << endl; // 输出 0
s = "loveleetcode";
cout << firstUniqChar(s) << endl; // 输出 2
s = "aabbcc";
cout << firstUniqChar(s) << endl; // 输出 -1
return 0;
}
```
首先使用 `unordered_map` 统计每个字符出现的频率,然后再遍历一次字符串,找到第一个出现次数为1的字符。如果没有出现次数为1的字符,则返回 -1。
相关问题
写一个c++代码 给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
下面是C++的实现代码:
```c++
#include <iostream>
#include <unordered_map>
using namespace std;
int firstUniqChar(string s) {
unordered_map<char, int> freq;
for (char c : s) {
freq[c]++;
}
for (int i = 0; i < s.size(); i++) {
if (freq[s[i]] == 1) {
return i;
}
}
return -1;
}
int main() {
string s = "leetcode";
int res = firstUniqChar(s);
cout << res << endl; // 输出 0
return 0;
}
```
该算法的时间复杂度是O(n),其中n是字符串的长度。首先,我们使用一个哈希表记录每个字符在字符串中出现的次数。然后,我们遍历字符串,找到第一个出现次数为1的字符,返回其索引。如果没有找到这样的字符,则返回-1。
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。用DEVc++实现
好的,下面是 DEV-C++ 的代码实现:
```cpp
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
int firstUniqChar(string s) {
unordered_map<char, int> charCount;
for (char c : s) {
charCount[c]++;
}
for (int i = 0; i < s.length(); i++) {
if (charCount[s[i]] == 1) {
return i;
}
}
return -1;
}
int main() {
string s = "leetcode";
int result = firstUniqChar(s);
cout << result << endl; // 输出 0
return 0;
}
```
这个函数的实现和上面的 C++ 代码是一样的。你可以在 DEV-C++ 中创建一个新的 C++ 项目,然后将这个代码复制到 `main.cpp` 中,然后编译运行即可。
阅读全文
相关推荐
















