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.
#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
int firstUniqChar(string s) {
int num[26] = {0};
for(int i=0;i<s.length();i++)
{
int index = s[i] - 'a';
num[index]++;
}
for(int i=0;i<s.length();i++)
{
int index = s[i] - 'a';
if(num[index] == 1)
return i;
}
return -1;
}
};
本文介绍了一个简单的算法问题:在一个字符串中找到第一个不重复的字符并返回其索引位置。通过遍历字符串两次的方式,首先统计每个字符出现的次数,然后再次遍历来找出首个仅出现一次的字符。
315

被折叠的 条评论
为什么被折叠?



