1. 程式人生 > >[劍指offer] 第一個只出現一次的字元[ Python]

[劍指offer] 第一個只出現一次的字元[ Python]

題目要求:在一個字串(1<=字串長度<=10000,全部由字母組成)中找到第一個只出現一次的字元,並返回它的位置

解題思路:

1.找出字串中共有幾個不同的字元

2.找出僅出現過一次的字元,並獲取他們各自的索引

3.返回最小的索引

# -*- coding:utf-8 -*-

class Solution:
    def FirstNotRepeatingChar(self, s):
        # write code here
        if s:
            res = []
            s_list = list(set(s))
            for i in s_list:
                if s.count(i) == 1:
                    res.append(s.index(i))
            return min(res)
        else:
            return -1