求解答下面这道题的完整代码(用C++),目前不太会用map,所以希望能不用就不用map,谢谢谢谢
求解答下面这道题的完整代码(用C++),目前不太会用map,所以希望能不用就不用map,谢谢谢谢wordpatternGivenapatternandastringstr...
求解答下面这道题的完整代码(用C++),目前不太会用map,所以希望能不用就不用map,谢谢谢谢word pattern
Given a pattern and a string str, find if str follows the same pattern.
Examples:
pattern = "abba", str = "dog cat cat dog" should return true.
pattern = "abba", str = "dog cat cat fish" should return false.
pattern = "aaaa", str = "dog cat cat dog" should return false.
pattern = "abba", str = "dog dog dog dog" should return false.
Notes:
Both pattern and str contains only lowercase alphabetical letters.
Both pattern and str do not have leading or trailing spaces.
Each word in str is separated by a single space.
Each letter in pattern must map to a word with length that is at least 1. 展开
Given a pattern and a string str, find if str follows the same pattern.
Examples:
pattern = "abba", str = "dog cat cat dog" should return true.
pattern = "abba", str = "dog cat cat fish" should return false.
pattern = "aaaa", str = "dog cat cat dog" should return false.
pattern = "abba", str = "dog dog dog dog" should return false.
Notes:
Both pattern and str contains only lowercase alphabetical letters.
Both pattern and str do not have leading or trailing spaces.
Each word in str is separated by a single space.
Each letter in pattern must map to a word with length that is at least 1. 展开
展开全部
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
bool match(const std::string &pattern, const std::string &str)
{
bool result = true;
std::string word;
std::vector <std::string> word_list;
size_t size = pattern.size();
word_list.reserve(size);
std::istringstream read(str);
while (read >> word) word_list.push_back(word);
#if DEBUG
assert(size == word_list.size());
#endif
for (int i = 0; i < size; i ++)
{
for (int j = i + 1; j < size; j ++)
{
bool pattern_match = pattern[i] == pattern[j];
bool word_match = word_list[i] == word_list[j];
if (pattern_match != word_match)
{
result = false;
}
}
}
return result;
}
void checkAndPrintResult(const std::string &pattern, const std::string &str)
{
std::cout << "pattern = \"" << pattern << "\", str = \"" << str << "\" should return "
<< (match(pattern, str) ? "true" : "false") << ".\n";
}
int main()
{
checkAndPrintResult("abba", "dog cat cat dog");
checkAndPrintResult("abba", "dog cat cat fish");
checkAndPrintResult("aaaa", "dog cat cat dog");
checkAndPrintResult("abba", "dog dog dog dog");
return 0;
}
图省事的做法,时间复杂度 O((pattern.size()^2), 不是很优化,但您未在描述中提出数据范围等。
未使用 map
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询