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.
本题题意很简单,就是寻找第一个不重复的元素,先做一遍统计,然后遍历即可得到答案
下面是C++的做法,
代码如下:
#include <iostream>
#include <vector>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <queue>
#include <stack>
#include <string>
#include <climits>
#include <algorithm>
#include <sstream>
#include <functional>
#include <bitset>
#include <numeric>
#include <cmath>
#include <regex>
using namespace std;
class Solution
{
public:
int firstUniqChar(string s)
{
vector<int> count(26, 0);
for (char c : s)
count[c - 'a']++;
for (int i = 0; i < s.length(); i++)
{
if (count[s[i] - 'a'] == 1)
return i;
}
return -1;
}
};