387. First Unique Character in a String

1.问题描述

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.
来自 https://leetcode.com/problems/first-unique-character-in-a-string/description/

2.题目分析

查找字符串中只出现一次的字母,并返回其下表。因此,先遍历一遍,记录26个字母出现的次数,生成table表,再遍历一遍字符串的每一个字母,并查表得出其对应的个数,当出现次数为1时,符合要求,结束并返回下标。

3.C++代码

//我的代码:(beats 99%)
int firstUniqChar(string s) 
{
    int talble[26] = { 0 };
    for (int i = 0; i < s.length(); i++)
        talble[s[i] - 'a']++;
    for (int j = 0; j < s.length(); j++)
    {
        if (talble[s[j] - 'a'] == 1)
            return j;
    }
    return -1;      
}

猜你喜欢

转载自blog.csdn.net/qq_29689907/article/details/80219218