字符串--3-第一个不重复字符

题目

在一个字符串(1<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置。

思路

建立一个哈希表,第一次扫描的时候,统计每个字符的出现次数。第二次扫描的时候,如果该字符出现的次数为1,则返回这个字符的位置。

#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;

class Solution
{
public:
	int firstNotRepeatStr(string str)
	{
		if (str.size() <= 0)
			return -1;

		unordered_map<char, int> countRepeat;
		int i;
		for (i = 0; i < str.size(); i++)
			countRepeat[str[i]]++;
		for (i = 0; i < str.size(); i++)
		{
			if (countRepeat[str[i]] == 1)
				return i;
		}
	}
};

int main()
{
	Solution s;
	string str = "bccabadfba";
	cout << s.firstNotRepeatStr(str) << endl;

	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/ax_hacker/article/details/80840878