劍指offer 第一個只出現一次的字符

題目

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

思路

用字典記錄所有字符出現次數。

代碼

# -*- coding:utf-8 -*-
class Solution:
    def FirstNotRepeatingChar(self, s):
        # write code here
        if not s: return -1
        tmp_dict = {}
        for c in s:
            if c in tmp_dict: tmp_dict[c] += 1
            else: tmp_dict[c] = 1
        for i, c in enumerate(s):
            if tmp_dict[c] == 1:
                return i
發佈了572 篇原創文章 · 獲贊 47 · 訪問量 30萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章