C++给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。 输入: 示例: leetcode loveleetcode 输出: 0 2 提示:你可以假定该字符串只包含小写字母。
时间: 2024-02-22 09:00:35 浏览: 19
好的,下面是 C++ 的代码实现,和 Python 代码类似:
```cpp
#include <string>
#include <unordered_map>
using namespace std;
class Solution {
public:
int firstUniqChar(string s) {
unordered_map<char, int> char_freq;
for (char c : s) {
char_freq[c]++;
}
for (int i = 0; i < s.size(); i++) {
if (char_freq[s[i]] == 1) {
return i;
}
}
return -1;
}
};
```
你可以通过调用 `Solution` 类中的 `firstUniqChar()` 函数来得到字符串中第一个不重复的字符的索引。例如:
```cpp
string s = "leetcode";
Solution solu;
cout << solu.firstUniqChar(s) << endl; // 输出 0
s = "loveleetcode";
cout << solu.firstUniqChar(s) << endl; // 输出 2
```
相关问题
写一个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` 中,然后编译运行即可。