如果两个英文单词,组成它们的字符集合相同,而且相同字符出现的次数也相同,则称这两个词匹配:比如说:同”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; }