首页 > 试题广场 >

如果两个英文单词,组成它们的字符集合相同,而且相同字符出现的

[问答题]
如果两个英文单词,组成它们的字符集合相同,而且相同字符出现的次数也相同,则称这两个词匹配:比如说:同”abbc”与词 ”babc”是匹配的。有一个词典,存储在字符串数组const char* dictionary[n]中,数组的每一个元素是一个词。对于任意给出的句子。句子中的单词使用空格分割。请实现以下函数,判断句子中是否有词和词典中的词匹配。
bool is_matching( const char* dictionary[],int n, const char* sentence);
/*
题目描述
如果两个英文单词,组成它们的字符集合相同,而且相同字符出现的次数也相同,则称这两个词匹配:
比如说:同”abbc”与词 ”babc”是匹配的。有一个词典,存储在字符串数组const char* dictionary[n]中,
数组的每一个元素是一个词。对于任意给出的句子。句子中的单词使用空格分割。

请实现以下函数,判断句子中是否有词和词典中的词匹配。
bool is_matching( const char* dictionary[],int n, const char* sentence);
*/

#include <iostream>
#include <cstdlib>
#include <vector>

using namespace std;

bool isMatch(const char*str1, const char *str2)
{
	int len1 = 0, len2 = 0;
	const char *p = str1, *q = str2;
	/*求两个字符串长度*/
	while (*p++ != '\0')
		++len1;
	while (*q++ != '\0')
		++len2;

	if (len1 != len2)
		return false;

	vector<char> vMap(256, 0);
	p = str1;
	while (*p != '\0')
	{
		++vMap[*p];
		++p;
	}//while

	/*验证匹配性*/
	q = str2;
	while (*q != '\0')
	{
		if (--vMap[*q] < 0)
			return false;
		++q;
	}//while
	return true;
}

bool is_matching(const char* dictionary[], int n, const char* sentence)
{
	if (!sentence)
		return false;

	int len = 0;
	const char *p = sentence;
	while (*p++ != '\0')
		++len;

	char *word = new char[len + 1];
	word[0] = '\0';

	/*单词长度计数sz*/
	int sz = 0;
	p = sentence;
	while (*p != '\0')
	{
		if (*p == ' ')
		{
			word[sz] = '\0';
			for (int i = 0; i < n; ++i)
			{
				if (isMatch(word,dictionary[i]))
					return true;
			}//for
			sz = 0;
			word[sz] = '\0';
		}
		else{
			word[sz++] = *p;
		}//else

		++p;
	}//while
	/*查找最后一个单词在不在词典中*/
	word[sz] = '\0';
	for (int i = 0; i < n; ++i)
	{
		if (isMatch(word, dictionary[i]))
			return true;
	}//for

	return false;
}

int main()
{
	const char *dictionary[] = { "I", "am", "a", "good", "student." };

	const char *s = "very good ";

	cout << is_matching(dictionary, 5, s) << endl;

	system("pause");
	return 0;


}

发表于 2016-03-03 16:36:13 回复(0)
Hash或者可以建立字典树判断
发表于 2015-06-11 20:57:50 回复(0)
abbc 和 babc 同的话, 即词语单个字符的ascii码和相同即词语相同。 把字符串比较转换成 int 型数字比较。
数组中所有词转换成int 放入 int数组。
比较大小
发表于 2014-11-14 13:35:24 回复(2)
判断词是否匹配可以用hash也可以用排序
发表于 2014-10-14 18:42:18 回复(0)