【求知=>算法】字符串中的第一个唯一字符

126 阅读2分钟

【求知=>算法】字符串中的第一个唯一字符

给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。

提示:

你可以假定该字符串只包含小写字母。

解题思路


  1. 统计字符串出现的次数的方式
  • 定义字符串s;
  • 将字符串转换成list集合并定义为list_s;
  • 获取集合的长度,定义为l;
  • 遍历数据统计每个字符串出现的次数,如果出现的次数等于1就把第一个数据下标返回,没有就返回-1。
# s = "leetcode"
s = "loveleetcode"
list_s = list(str(s)) # 将字符串转成集合

l = len(list_s) # 获取长度

for i in range(l):
    if list_s.count(list_s[i])==1:
        return list_s.index(list_s[i])
return -1

  1. 通过find和rfind的方式
  • 定义字符串s;
  • 遍历数据,如果从字符串左边开始查询子字符串匹配到的第一个索引和从字符串右边开始查询字符串匹配到的第一个索引相等,就把右边开始的第一个下标输出,没有就返回-1。
s = "leetcode"
# s = "loveleetcode"

for i in s:
    if s.find(i)==s.rfind(i):
        return s.find(i)
return -1
  1. 通过字典的方式
  • 定义字符串s;
  • 定义空字典dict;
  • 循环字符串,如果字符串不在dict字典中、就把统计每个字符串出现的次数添加到字典(dict)中;
  • 循环字典的key,如果统计每个字符串出现的次数等1、就把第一个数据下标返回,没有就返回-1。
s = "leetcode"
# s = "loveleetcode"
dict = {}

for i in s:
    if i not in dict:
        dict.update({i:s.count(i)})

for y in dict.keys():
    if dict[y] ==1:
        return s.index(y)
return -1

# 第二种方式
s = "leetcode"
# s = "loveleetcode"

d = {}
for i in s:
    if i not in d:
        d[i] = 1
    else:
        d[i] += 1

for x, v in d.items():
    if v == 1:
        return s.index(x)
else:
    return -1

  1. 通过内置Counter方式
  • 定义字符串s;
  • 通过Counter来统一出现的次数并定义为temp;
  • 遍历数据,如果temp次数等于1,就把第一个数据下标返回,没有就返回-1。

import collections
# s = "leetcode"
s = "loveleetcode"
temp = collections.Counter(s)

for i in range(len(s)):
    if temp[s[i]] == 1:
        return i
return -1

知识扩展


count()方法的使用

find()与rfind()方法的使用

Counter类(计数器)的应用