LeetCode 笔试题 First Unique Character in a String (找到第一个不重复的字符)

问题描述

给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。

案例:

s = "leetcode"
返回 0.

s = "loveleetcode",
返回 2.

**注意事项:**您可以假定该字符串只包含小写字母。

代码 

int findFirstUnique(string &str)
{
	int index = 0;//表示字符串的下标
	//从第一个字符开始判断,然后遍历后面的的字符是否有重复,
	//若无重复则返回当前的下标,有重复则继续判断下一个字符
	for (auto it = str.begin(); it != str. end();)
	{
		if (find(it + 1, str.end(), *it) != str.end())
		{
			it++;
			index++;
		}
		else
		{
			return index;
		}
		
	}
	return -1;
}
int main()
{
	string str = "leetcode";
	cout << findFirstUnique(str) << endl;
	getchar();
	return 0;
}

 

你可能感兴趣的:(LeetCode笔试题)