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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiaohuigou1786/article/details/82555580

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

我们的目的是从一串字符中找到第一个只出现一次的字符,对于这种问题没有好的方法,就是先遍历一遍字符串使用字典统计每个字符的个数,最重要的是使用queue这样一个list来保存所有第一次出现不同字符的index,例如输入字符串是‘google’,那么queue中保存的是0(第一个g的index),1(第一个o的index),4(第一个l的index),5(第一个e的index);所以第一个只出现一次的字符的index肯定在queue中,然后从queue中找到第一个只出现一次的字符的index。

代码如下:

# -*- coding:utf-8 -*-
class Solution:
    def FirstNotRepeatingChar(self, s):
        # write code here
        queue = []
        memories = {}
        for indx, ch in enumerate(s):
            if ch not in memories:
                queue.append(indx)
                memories[ch] = 0
            memories[ch] += 1
        while queue and (memories[s[queue[0]]]>1):
            queue.pop(0)
        return queue[0] if queue else -1

猜你喜欢

转载自blog.csdn.net/xiaohuigou1786/article/details/82555580