剑指offer:Python 第一个只出现一次的字符 多种方法实现 图解

题目描述

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

思路及Python实现

  • 这题和“字符流中第一个只出现一次的字符”题非常像,所以我们同样可以使用字典和队列来做,用字典来记录字符出现的次数,但是字典是无序的,无法保证出现次数为1的字符就是第一个出现的字符,因此,我们可以利用一个队列,来完成,当队首元素出现的次数为1时,那么这个元素一定是第一个只出现一次的,返回位置即可!
# 直接把上次题目的代码拿过来,在队列中添加元素
class Solution:
    def __init__(self):
        self.memory = {}
        self.queue = []

    def FirstNotRepeatingChar(self, s):
        if not s:
            return -1
        for item in s:
            if item not in self.memory:
                self.memory[item] = 0
            self.memory[item] += 1
            if self.memory[item] == 1: # 出现相同的元素不必重复添加
                self.queue.append(item)
        while self.queue and self.memory[self.queue[0]] > 1:
            self.queue.pop(0)
        return s.index(self.queue[0] if len(self.queue) else "")

# 测试
obj = Solution()
s = "google"
print(obj.FirstNotRepeatingChar(s))

也可以这样写,在队列中直接添加索引

class Solution:
    def FirstNotRepeatingChar(self, s):
        if s == "":
            return -1
        queue = []
        memories = dict()
        for index,ss in enumerate(s):
            if ss not in memories:
                queue.append(index)
                memories[ss] = 0
            memories[ss] += 1
        while queue and memories[s[queue[0]]]>1:
         # 找到队首元素所在位置的第一个出现次数为1的元素,返回位置
            queue.pop(0)
        return queue[0] if queue else -1 

在这里插入图片描述

# 利用数组建立 哈希表
class Solution:
    def FirstNotRepeatingChar(self, s):
        # write code here
        if s == ' ':
            return -1
        hashtable=[0]*256
        for i in s:
            hashtable[ord(i)] += 1
        for i in s:
            if hashtable[ord(i)]==1:
                return s.index(i)
        return -1
 
# 方法二:利用python自带的字典,两次遍历实现(不建议使用)
class Solution:
    def FirstNotRepeatingChar(self, s):
        # write code here
        if s==' ':
            return -1
        d=dict()
        #第一次遍历字符串,将每个字符的次数存入字典
        for i in s:    
            d[i]=d.get(i,0)+1
        #第二次遍历字符串,检查每个字符出现的次数
        for i in s:
            if d[i]==1:   # O(1)
                return s.index(i)
        return -1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值