【剑指】50(1).字符串中第一个只出现一次的字符

题目描述

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

算法分析

  • 用哈希表记录每个字符出现的个数,第一遍扫描这个string时,每碰到一个字符,在哈希表中找到对应的项并把出现的次数增加一次。第二次扫描时,返回第一个哈希表中记录次数为1的字符的位置。

提交代码:

class Solution {
public:
	/* ASCII码最多256个,可以使用vector模拟哈希表,也可以直接使用map */
	int FirstNotRepeatingChar(string str) {
		if (str.empty())
			return -1;

		vector<int> hashTable(256, 0);

		for (auto iter = str.cbegin(); iter != str.cend(); ++iter)
		{
			++hashTable[*iter];
		}

		for (int i = 0; i < str.length(); ++i)
		{
			if (hashTable[str[i]] == 1)
				return i;
		}

		return -1;
	}
};

测试代码:

// ====================测试代码====================
void Test(const string pString, int expected)
{
	Solution s;
	if (s.FirstNotRepeatingChar(pString) == expected)
		printf("Test passed.\n");
	else
		printf("Test failed.\n");
}

int main(int argc, char* argv[])
{
	// 常规输入测试,存在只出现一次的字符
	Test("google", 4);

	// 常规输入测试,不存在只出现一次的字符
	Test("aabccdbd", -1);

	// 常规输入测试,所有字符都只出现一次
	Test("abcdefg", 0);

	// 鲁棒性测试,输入nullptr
	Test(string(), -1);

	return 0;
}

猜你喜欢

转载自blog.csdn.net/ansizhong9191/article/details/81015481