剑指offer 34. 第一个只出现一次的字符

原题

在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).

Reference Answer

思路分析

直接遍历字符串,用python dict进行次数统计,最后返回目标值对应最小的index。

# -*- coding:utf-8 -*-
class Solution:
    def FirstNotRepeatingChar(self, s):
        # write code here
        temp_dict = {}
        temp_index = {}
        for index, value in enumerate(s):
            if value not in temp_dict:
                temp_dict[value] = 1
                temp_index[value] = index
            else:
                temp_dict[value] += 1
        print(temp_dict)
        print(temp_index)
        res = len(s)
        for key, value in temp_dict.items():
            if value == 1:
                res = min(res, temp_index[key])
        if res == len(s):
            return -1
        else:
            return res

                

猜你喜欢

转载自blog.csdn.net/Dby_freedom/article/details/84309673