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

題目描述

在一個字符串(0<=字符串長度<=10000,全部由字母組成)中找到第一個只出現一次的字符,並返回它的位置, 如果沒有則返回 -1(需要區分大小寫).

Solution

哈希表。

class Solution:
    def FirstNotRepeatingChar(self, s):
        if len(s) == 0:
            return -1
        hashmap = {}
        for index in range(len(s)):
            if s[index] in hashmap:
                hashmap[s[index]] += 1
            else:
                hashmap[s[index]] = 1
        for i in range(len(s)):
            if hashmap[s[i]] == 1:
                return i
        return -1
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章