剑指Offer(Python多种思路实现):第一个只出现一次的字符

面试50题:

题目:第一个只出现一次的字符

题:在一个字符串(1<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置。

解题思路一:利用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

解题思路二:

class Solution:
    def FirstNotRepeatingChar(self, s):
        # write code here
        if len(s)<=0:
            return -1
        
        char_dict={}
        for i in s:
            if i in char_dict:
                char_dict[i]+=1
            else:
                char_dict[i]=1
        for index,value in enumerate(s):
            if char_dict[value]==1:
                return index
        return -1
发布了62 篇原创文章 · 获赞 6 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_44151089/article/details/104524983