387. First Unique Character in a String - leetcode

xiaoxiao2021-02-28  78

387. First Unique Character in a String

Given a string, find the first non-repeatingcharacter in it and return it's index. If it doesn't exist, return -1.

Examples:

s = "leetcode"

return 0.

 

s = "loveleetcode",

return 2.

 

Note: You may assume the string contain onlylowercase letters.

 

题意说可以假设只有26个小写字母

这里我采用的方法是python中的dict字典,可以包含不仅是小写字母的键值,不过执行效率不怎么高。。

逻辑如下:遍历字符串S,如果没有出现在字典中,则初始化为1,否则就加1.这里统计的是出现的次数

然后再遍历S,如果对应的键值在字典中的value1,代表只出现了一次,则返回这个k在字符串S中的索引。

最后如果不存在则返回-1

class Solution(object): deffirstUniqChar(self, s): """ :type s: str :rtype: int """ d={} fori in s: if i not in d: d[i]=1 else: d[i]=int(d[i])+1 #value +1 fork in s: if(d[k]==1): return s.index(k) return -1

另外,还可以利用从0-25对应起相应的26个字母,再通过遍历字符串计数,相关判断后返回。

另外,还可以运用HashMap

转载请注明原文地址: https://www.6miu.com/read-79760.html

最新回复(0)