C++程序:检查给定单词是否符合给定模式
假设我们有一个模式p和一个字符串str,我们需要检查str是否遵循相同的模式。这里的遵循是指模式中的一个字母和str中一个非空单词之间存在双射关系。
因此,如果输入类似于pattern = "cbbc",str = "word pattern pattern word",则输出为True。
为了解决这个问题,我们将遵循以下步骤:
strcin := str
定义一个数组words
对于strcin中的每个单词
将单词插入到words的末尾
定义一个映射p2i
i := 0
pat := 空字符串
对于pattern中的每个字符c:
如果c不是p2i的成员,则:
(将i加1)
p2i[c] := i
pat := pat连接p2i[c]
定义一个映射str2i
i := 0
pat1 := 空字符串
对于words中的每个单词c:
如果c不是str2i的成员,则:
(将i加1)
str2i[c] := i
pat1 := pat1连接str2i[c]
当pat1与pat相同时返回true
示例
让我们来看下面的实现,以便更好地理解:
#include <bits/stdc++.h> using namespace std; class Solution { public: bool wordPattern( string pattern, string str ) { istringstream strcin(str); string word; vector<string> words; while (strcin >> word) words.push_back(word); unordered_map<char, int> p2i; int i = 0; string pat = ""; for (auto c : pattern) { if (p2i.count(c) == 0) { i++; p2i[c] = i; } pat += to_string(p2i[c]); } unordered_map str2i; i = 0; string pat1 = ""; for (auto c : words) { if (str2i.count(c) == 0) { i++; str2i[c] = i; } pat1 += to_string(str2i[c]); } return pat1 == pat; } }; main(){ Solution ob; cout << (ob.wordPattern("cbbc", "word pattern pattern word")); }
输入
"cbbc", "word pattern pattern word"
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输出
1
广告