Quantcast
Channel: 书影 - Entries for the tag leetcode
Viewing all articles
Browse latest Browse all 559

[LeetCode]First Unique Character in a String

$
0
0

题目描述:

LeetCode 387. 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:

s = "leetcode"
return 0.

s = "loveleetcode",
return 2.

Note: You may assume the string contain only lowercase letters.

题目大意:

给定一个字符串,寻找第一个不重复字符并返回其下标。如果不存在,返回-1。

注意:你可以假设字符串不包含小写字母。

解题思路:

首先统计每个字符的出现次数,然后遍历一次原字符串。

Python代码:

class Solution(object):
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        d = collections.Counter(s)
        ans = -1
        for x, c in enumerate(s):
            if d[c] == 1:
                ans = x
                break
        return ans

 


Viewing all articles
Browse latest Browse all 559

Trending Articles