[topcoder]HappyLetterDiv2

http://community.topcoder.com/stat?c=problem_statement&pm=13245

就是有字符串,里面的字符可以随意两两消除,如果不等的话,那么最后如果留下一个字符,这个字符就是winning letter。如果任意方法消除都是这个winning letter,叫做happy letter。求happy letter是否存在。题目其实就是找众数。要注意的是求完了还要扫一遍是不是大于length/2。

#include <string>

using namespace std;

class HappyLetterDiv2 {
public:
	char getHappyLetter(string letters)
	{
		char ch = letters[0];
		int count = 1;
		int n = letters.size();
		for (int i = 1; i < n; i++)
		{
			if (count > 0 && letters[i] != ch)
			{
				count--;
			}
			else // count == 0 || letters[i] == ch
			{
				count++;
				ch = letters[i];
			}
		}
		count = 0;
		for (int i = 0; i < n; i++)
		{
			if (letters[i] == ch)
				count++;
		}
		if (count > n / 2)
			return ch;
		else
			return ‘.‘;
	}
};

  

[topcoder]HappyLetterDiv2,布布扣,bubuko.com

[topcoder]HappyLetterDiv2

上一篇:android database 相关


下一篇:带固态硬盘的电脑Ubuntu和Windows双系统安装