给定一个字符串和长度为n的字符串,找到其中第一个不重复的字符并返回其索引。如果不存在,则返回-1
时间: 2024-05-08 08:18:25 浏览: 9
好的,您的问题是:给定一个字符串和长度为n的字符串,找到其中第一个不重复的字符并返回其索引。如果不存在,则返回-1。
我可以给您提供一个Python的解法,代码如下:
```
def firstUniqChar(s: str) -> int:
# 构建哈希表
char_dict = {}
for char in s:
if char in char_dict:
char_dict[char] += 1
else:
char_dict[char] = 1
# 查找第一个不重复的字符
for i in range(len(s)):
if char_dict[s[i]] == 1:
return i
return -1
```
这个算法的时间复杂度是O(n),因为我们需要扫描整个字符串。我们使用一个哈希表来存储每个字符出现的次数,然后再次遍历字符串,找到第一个出现次数为1的字符。
如果您有任何疑问,请随时告诉我。
相关问题
给定一个字符串和长度为n的字符串,找到其中第一个不重复的字符并返回其索引。如果不存在,则返回-1(c++语言)
你可以使用哈希表来解决这个问题。先遍历一遍字符串,将每个字符出现的次数记录在哈希表中。再遍历一遍字符串,找到第一个出现次数为1的字符,返回它的索引即可。如果不存在出现次数为1的字符,返回-1。以下是C语言代码实现:
int firstUniqChar(char *s, int n) {
if (n == 0) return -1;
int freq[26] = {0}; // 哈希表,记录每个字符出现的次数
// 统计每个字符出现的次数
for (int i = 0; i < n; i++) {
freq[s[i] - 'a']++;
}
// 找到第一个出现次数为1的字符
for (int i = 0; i < n; i++) {
if (freq[s[i] - 'a'] == 1) {
return i;
}
}
return -1;
}
Python给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
方法一:
```python
def first_not_repeating_char(strings):
chars = []
times = []
for s in strings:
if s not in chars:
chars.append(s)
times.append(1)
else:
char_index = chars.index(s)
times[char_index] += 1
for t in times:
if t == 1:
times_index = times.index(t)
return chars[times_index]
return -1
strings = input('请输入长字符串:')
print('结果:', first_not_repeating_char(strings))
```
方法二:
```python
from collections import Counter
def deal_str(s):
counter = Counter(s)
singles = [_c for _c, _i in counter.items() if _i == 1]
idxs = [s.index(_c) for _c in singles]
idx = min(idxs) if idxs else -1
print(f"字符串({s})中的第一个不重复字符的位置是({idx})")
string = "abcab"
deal_str(string)
```
方法三:
```python
def deal_str2(s):
my_dict = {}
idx = -1
for _i, _c in enumerate(s):
if _c not in my_dict:
my_dict[_c] = _i
else:
my_dict[_c] = 9999
idx = min(my_dict.values())
idx = -1 if idx >= 9999 else idx
print(f"字符串({s})中的第一个不重复字符的位置是({idx})")
string = "abcab"
deal_str2(string)
```