题目:
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.
大意:找到给出字符串中第只出现一次的字母
解答:
//387. First Unique Character in a String
//设置一个26长的整形数组用来存储字符串s中各个字母的频率
//再次遍历字符串,返回找到的第一个频率为1的字母的地址
//如果都不是1,返回-1
int firstUniqChar(string s) {
vector<int> count(26, 0); //##
//将词s字母频计入表中
int len = s.size();
for (int i = 0; i < len; i++) //##
count[s[i] - 'a'] ++; //##
for (int j = 0; j < len; j++)
if (count[s[j] - 'a'] == 1)
return j;
return -1;
}//(38ms,97.97%)
文章中加##的是一个常用的记录字符串字母频率的方法:
vector<int> count(26, 0);
for (int i = 0; i < s.size(); i++)
count[s[i] - 'a'] ++;