50-01 第一个只出现一次的字符

问题

题目

在字符串中找出第一个只出现一次的字符的索引。如输入"abaccdeff",则输出1,如果没有这样的字符存在,则返回-1,要求时间复杂度为O(n)。

LeetCode

C++ 题解

class Solution {
public:
    int firstUniqChar(string s) {
        // 创建一个计数表
        int cnt[256] = {0};
        // 遍历字符串,统计字符出现的个数
        for (int i=0;i<s.size();i++)
            cnt[s[i]]++;
        
        // 在此遍历字符串,返回第一个只出现一次的字符的序号
        for (int i=0;i<s.size();i++)
            if (cnt[s[i]]== 1)
                return i;
        
        return -1;

    }
};

python 题解

方法一

class Solution(object):
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        hash_map = {}
        for c in s:
            if c not in hash_map:
                hash_map[c] = 1
            else:
                hash_map[c] += 1
        
        for i in range(len(s)):
            c = s[i]
            if c in hash_map and hash_map[c] == 1:
                return i
        
        return -1

方法二

class Solution(object):
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        letters='abcdefghijklmnopqrstuvwxyz'
        index = [s.index(l) for l in letters if s.count(l) == 1]
        
        if len(index) > 0:
            return min(index)
        else:
            return -1
posted @ 2019-01-31 15:06  youngliu91  阅读(134)  评论(0)    收藏  举报