卖萌的弱渣

I am stupid, I am hungry.

First Unique Character in a String

Given a string, find the first non-repeating character in it and return it’s index. If it doesn’t exist, return -1.

Examples:

1
2
3
4
5
s = "leetcode"
return 0.

s = "loveleetcode",
return 2.

Note:

You may assume the string contain only lowercase letters.

Solution

(First-Unique-Character-in-A-String.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution(object):
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        if not s:
            return -1
        hash_table = dict()
        for c in s:
            if hash_table.get(c) == None:
                hash_table[c] = 1
            else:
                hash_table[c] += 1

        for i in range(len(s)):
            if hash_table[s[i]] == 1:
                return i
        return -1