写出代码:给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
时间: 2023-11-24 07:09:18 浏览: 94
以下是使用 Python 3 实现的代码:
```python
def firstUniqChar(s: str) -> int:
char_count = {}
for char in s:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
for idx, char in enumerate(s):
if char_count[char] == 1:
return idx
return -1
```
我们首先构建一个字典 `char_count`,用于存储每个字符在字符串中出现的次数。然后遍历一遍字符串,统计每个字符出现的次数。接着再次遍历字符串,找到第一个出现次数为 1 的字符并返回它的索引。如果没有找到,则返回 -1。
相关问题
用从c++写出代码:给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
以下是用 c++ 实现的解决方案:
```c++
#include <iostream>
#include <unordered_map>
using namespace std;
int firstUniqChar(string s) {
unordered_map<char, int> charMap;
for (char c : s) {
charMap[c]++;
}
for (int i = 0; i < s.length(); i++) {
if (charMap[s[i]] == 1) {
return i;
}
}
return -1;
}
int main() {
string s = "leetcode";
int index = firstUniqChar(s);
cout << index << endl; // 输出 0
return 0;
}
```
此代码中,我们使用了一个哈希表来记录每个字符出现的次数。然后我们遍历一遍字符串,找到第一个出现次数为 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。