同构字符串
class Solution {
public:
bool isIsomorphic(string s, string t) {
//使用map映射机制么?
//对于map的特性是key不可以重复的,但是value可以重复,所以需要再value上加功夫
map<char,char> yingshe;
int used[128]={0};
int len=s.size();
if(len==0)
return true;
//开始建立映射关系
for(int i=0;i<len;++i)
{
char c1=s[i];
char c2=t[i];
if(yingshe.find(c1)!=yingshe.end())
{
if(c2!=yingshe[c1])
return false;
}
else
{
if(used[c2]==1)
return false;
yingshe[c1]=c2;
used[c2]=1;
}
}
return true;
}
};
单词规律
class Solution {
public:
bool wordPattern(string pattern, string str) {
//需要获取字符串的元素
//这里需要真正遍历一下map容器了
map<string,char> yingshe;
string word;
int index = 0;
int used[128] = { 0 };
str.push_back(' ');
for (auto c : str)
{
if (c == ' ')
{
if (yingshe.find(word) != yingshe.end())//如果存在了
{
if (pattern[index] != yingshe[word])
return false;
}
else//如果不存在的话,加入
{
//如果已经被使用过了,那么退出
if (used[pattern[index]] == 1)
return false;
yingshe[word] = pattern[index];
used[pattern[index]] = 1;//该字符串被使用过了,标记一下
}
word = "";
++index;
//如果超越了边界,也就是匹配串比较长,那么退出
if (index == (pattern.size()+1) )
return false;
}
else
word = word + c;
}
//也就是模式串长
if (index != (pattern.size()))
return false;
return true;
}
};
这两种题目都可以用map映射机制,然后设定一个数组来存储已经用过的字符