【初级算法】字符串中的第一个唯一字符 2021.8.17

【题目】字符串中的第一个唯一字符

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

 

示例:

s = "leetcode"
返回 0

s = "loveleetcode"
返回 2
 

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

作者:力扣 (LeetCode)
链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xn5z8r/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 

1.0 自己做

1 class Solution:
2     def firstUniqChar(self, s: str) -> int:
3         length = len(s)
4         for i in range(length):
5             number_of = s.count(s[i])
6             if number_of == 1:
7                 return s.index(s[i])
8         return -1

 

 我醉了,结果出来的瞬间不厚道的笑了出声,居然这么长时间。

最开始还是想的笨方法,对字符串的函数不太熟悉,脑海中没有多少能用的方法。

后来查了一下方法,发现了个count能用。

我需要一个用时更短的方法。

 

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

这句话要如何用呢?

 

2.0 学习

 

2.1 方法一

1 class Solution:
2     def firstUniqChar(self, s: str) -> int:
3         for i in range(len(s)):
4             if s.find(s[i])==s.rfind(s[i]):
5                 return i
6         return -1

 

 Python rfind() 返回字符串最后一次出现的位置,如果没有匹配项则返回 -1。

 

 

2.2 pythonic算法

1 class Solution:
2     def firstUniqChar(self, s: str) -> int:
3         if len(s) == 1:
4             return 0
5         for i in range(len(s)):
6             if s[i] not in s[:i] and s[i] not in s[i+1: ]:
7                 return i
8         return -1

 

 

 

2.3 哈希算法

 1 class Solution:
 2     def firstUniqChar(self, s: str) -> int:
 3         words = [chr(i) for i in range(97, 123)]
 4         values = [0] * 26
 5         wordsDic = dict(zip(words, values))
 6         for word in s:
 7             wordsDic[word] += 1
 8         for i in range(len(s)):
 9             if wordsDic[s[i]] == 1:
10                 return i
11         return -1

 

 

 

 

chr() 函数:chr() 用一个范围在 range(256)内的(就是0~255)整数作参数,返回一个对应的字符。

 

 

 

 

https://www.cnblogs.com/anita-harbour/p/9328597.html

posted @ 2021-08-17 09:19  阿吽  阅读(80)  评论(0)    收藏  举报