[LeetCode]First Unique Character in a String

题目描述:

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

 

本文链接:http://bookshadow.com/weblog/2016/08/21/leetcode-first-unique-character-in-a-string/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码

Pingbacks已关闭。

暂无评论

张贴您的评论