题目:字符串中的第一个唯一字符
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
案例:
s = "leetcode"
返回 0.
s = "loveleetcode",
返回 2.
注意事项:您可以假定该字符串只包含小写字母。
解答:
用哈希表建立每个字符和其出现次数的映射,然后按顺序遍历字符串,找到第一个出现次数为1的字符,返回其位置即可。
代码示例:
1.封装类
class Solution
{
public:
int firstUniqChar(string s)
{
unordered_map<char, int> m;
for (char c : s)
m[c]++;
for (int i = 0; i < s.size(); ++i)
{
if (m[s[i]] == 1)
return i;
}
return -1;
}
};
分析:unordered_map<char, int> m;
这行代码建立一个容器,内部数据结构为哈希表
for (char c : s)
定义一个遍历字符c,让它分别等于字符串数组s里面的各个字符,然后执行下面的语句.当c被赋值为chars里面所有字符各一次后,就会退出这个循环
m[c]++;计算哈希表里出现相同字母的次数
之后的for()循环,判断第一次出现唯一出现的字母,若有返回i值(字母所处位置),若没有,返回-1.
2.头文件
#include<iostream>
#include<string>
#include <unordered_map>
using namespace std;
3.主函数
int main()
{
string a = "loveleetcode";
class Solution pt;
int b = pt.firstUniqChar(a);
cout << b << endl;
}
分析:定义变量,用类处理,输出结果。
写的代码都在VS2015下测试没有问题,如果输入为string a = "loveleetcode";
该题所有测试代码如下
#include<iostream>
#include<string>
#include <unordered_map>
using namespace std;
class Solution
{
public:
int firstUniqChar(string s)
{
unordered_map<char, int> m;
for (char c : s)
m[c]++;
for (int i = 0; i < s.size(); i++)
{
if (m[s[i]] == 1)
return i;
}
return -1;
}
};
int main()
{
string a = "loveleetcode";
class Solution pt;
int b = pt.firstUniqChar(a);
cout << b << endl;
}