给定一种规律pattern和一个字符串s,判断s是否遵循相同的规律。
这里的[遵循]指完全匹配,例如,pattern里的每个字母和字符串s中的每个非空单词之间存在着双向连接的对应规律。
示例1:
输入: pattern = "abba", s = "dog cat cat dog"
输出: true
示例 2:
输入:pattern = "abba", s = "dog cat cat fish"
输出: false
示例 3:
输入: pattern = "aaaa", s = "dog cat cat dog"
输出: false
示例 4:
输入: pattern = "aaa", s = "dog dog dog dog"
输出: false
解析:先拆分字符s为单独的单词数组
比较数组s,和单词数组的映射是否唯一。
示例源码:
// Len_WordPattern.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <string>
#include <map>
#include <stdio.h>
#include <vector>
using namespace std;
// 拆分字符串,vector数组
vector<string> SplidAllString(string s)
{
vector<string> result;
int count = 0;
char temp[28] = { '0' };
count = 0;
for (int t = 0; t < s.size(); t++)
{
if (s[t] != ' ')
{
temp[count++] = s[t];
}
else
{
if (strlen(temp) > 0)
{
result.push_back(temp);
}
memset(temp, 0, sizeof(temp));
count = 0;
}
}
if (strlen(temp) > 0)
{
result.push_back(temp);
}
memset(temp, 0, sizeof(temp));
return result;
}
bool wordPattern(string pattern, string s)
{
// 拆分字符串
vector<string> st = SplidAllString(s);
// 比较数组长度,长度不一致,则失败
if (st.size() != pattern.size())
{
return false;
}
// 构造两个map,分别实现pattern->s的映射,和s->pattern的映射;
// 当正映射和逆映射不唯一的时候,失败
map<char, string> map1;
map<string, char> map2;
for (int i = 0; i < pattern.size(); i++)
{
if (map1.find(pattern[i]) != map1.end() && strcmp(map1[pattern[i]].c_str(), st[i].c_str()) != 0)
{
return false;
}
else if (map2.find(st[i]) != map2.end() && map2[st[i]] != pattern[i])
{
return false;
}
else
{
map1.insert(pair<char, string>(pattern[i], st[i]));
map2.insert(pair<string, char>(st[i], pattern[i]));
}
}
return true;
}
void PrintString(string s1, string s2, int nResult)
{
printf("\ns1 = \"%s\", s2 = \"%s\", result = %s\n", s1.c_str(), s2.c_str(), (nResult != 0) ? ("true") : ("false"));
}
int main()
{
string s1 = "abba";
string s2 = "dog cat cat dog";
int nResult = wordPattern(s1, s2);
PrintString(s1, s2, nResult);
s1 = "abba";
s2 = "dog cat cat fish";
nResult = wordPattern(s1, s2);
PrintString(s1, s2, nResult);
s1 = "aaaa";
s2 = "dog cat cat dog";
nResult = wordPattern(s1, s2);
PrintString(s1, s2, nResult);
s1 = "aaa";
s2 = "dog dog dog dog";
nResult = wordPattern(s1, s2);
PrintString(s1, s2, nResult);
}
执行结果: