【面试题001】求出句子中没有出现过的所有字母

假如一个句子含有所有字母,就叫做pangrams. 比如:
"A quick brown fox jumps over the lazy dog" 就是一个pangrams.

要求写一个C++函数, string getMissingLetters(const string& sA)
这里sA 代表一个输入的句子。
假如sA 不是pangrams, 那么函数应该输出所有sA缺失的字母。 输出的字母应该按字典顺序排列。

btw:
字母不区分大小写,最后输出小写字母

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

string getMissingLetters(const string& sA);
int _tmain(int argc, _TCHAR* argv[])
{
	

	//string strSentence = "jumps over the lazy dog";
	string strSentence = " ";
	string missingLetters = getMissingLetters(strSentence);
	cout << missingLetters << endl;
	return 0;
}

string getMissingLetters(const string& sA)
{
	int letterFre[256] = {0};
	int occurLetterNum = 0;
	for (int i = 0;i<sA.size();i++)
	{
		char ch = sA[i];
		//如果是大写字母,先转成小写
		if (ch >= 'A' && ch <= 'Z')
		{
			ch = 'a' + (ch - 'A');
		}

		//非字母的过掉
		if (ch < 'a' || ch > 'z' )
		{
			continue;
		}

		//统计出现过的字母的个数
		if (letterFre[(int)ch] == 0)
		{
			occurLetterNum ++;
		}
		letterFre[(int)ch] ++;
	}
	//没出现的字母当然是26 - occurLetterNum
	string missLetters(26 - occurLetterNum,' ');


	//将没出现的字母们拎出来
	int count = 0;
	for (int i = 'a';i <= 'z';i++)
	{
		if (letterFre[i] == 0)
		{
			missLetters[count++] = (char)i;
		}
	}
	return missLetters;

}

posted on 2011-06-04 15:34  speedmancs  阅读(286)  评论(0编辑  收藏  举报

导航