劍指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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章