1. 程式人生 > >劍指Offer32:第一個只出現一次的字元

劍指Offer32:第一個只出現一次的字元

思路:

利用雜湊表,雜湊表的下標是字元的ASCII值,值為字元出現的次數。

# -*- coding:utf-8 -*-
class Solution:
    def FirstNotRepeatingChar(self, s):
        # write code here
#建立雜湊表,字元長度為8的資料型別,共有256種可能,於是建立一個長度為256的列表
        ls=[0]*256
        #遍歷字串,下標為字元的ASCII值,值為該字元出現的次數
        for i in s:
            ls[ord(i)]+=1
        #遍歷列表,找到出現次數為1的字元並輸出位置
        for j in s:
            if ls[ord(j)]==1:
                return s.index(j)
        return -1
            

另一種做法:

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

count()函式可以統計每個字元出現的個數。