0
点赞
收藏
分享

微信扫一扫

剑指offer50 第一个只出现一次的字符


在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写)

解题思路:

第一:利用python特性 

string.count(str) 返回 str 在 string 里面出现的次数,利用python此特性可以几行代码搞定

class Solution:
def FirstNotRepeatingChar(self, s):
# write code here
if not s or len(s)<=0:
return -1
for i in s:
if s.count(i)==1:
return s.index(i)
return -1

第二:利用哈希表特性

自定义一个哈希表,利用每个字母的ASCII码来作为数组的index,用一个58长度的数组来存储每个字母出现的次数,为什么是58呢,主要是由于A-Z对应的ASCII码为65-90,a-z对应的ASCII码值为97-122,而每个字母的index=int(word)-65,比如g=103-65=38,而数组中具体记录的内容是该字母出现的次数,最终遍历一遍字符串,找出第一个数组内容为1的字母就可以了,时间复杂度为O(n)。

class Solution(object):
def searchSingleChar(self, string):
list = []
for value in range(0, 58):
list.append(0)

for character in string:
count = list[ord(character) - 65]
list[ord(character) - 65] = count + 1

for index, character in enumerate(string):
if list[ord(character) - 65] == 1:
return index



obj = Solution()
characterIndex = obj.searchSingleChar('thisistestdemothisistestdemoX')
print("出现一次的第一个字母下标是: %d" % (characterIndex))

 

举报

相关推荐

0 条评论