Wins the offer - the first characters appear only once

Title Description

In one string (0 <= length of the string <= 10000, all of the alphabet) find a first character appears only once, and returns to its position, or -1 if not (case-sensitive).

Thinking

Is the hash table, keep the number of each character

# -*- coding:utf-8 -*-
import collections
class Solution:
    def FirstNotRepeatingChar(self, s):
        chars = collections.defaultdict(lambda:0)
        for c in s:
            chars[c]+=1
        for c in s:
            if chars[c] == 1:
                return s.index(c)
        return -1

 

Published 82 original articles · won praise 2 · Views 4357

Guess you like

Origin blog.csdn.net/qq_22498427/article/details/104782217