查找两个字符串是否是同构字符串
题目:给定两个字符串s1和s2,判断它们是否是同构的。
如果s1中的字符可以按某种映射关系替换得到s2,那么这两个字符串是同构的。
要求:每个出现的字符都应当映射到另一个字符,同时不改变字符的顺序。不同字符
不能映射到同一个字符上,相同字符只能映射到同一个字符上,字符可以映射到自己本身。
示例 1:
输入:s1 = "egg", s2 = "add"
输出:true
示例 2:
输入:s1 = "foo", s2 = "bar"
输出:false
示例 3:
输入:s1 = "paper", s2 = "title"
输出:true
解析: 同时构造两个map<char, char>, 一个是s1到s2的映射, 一个是s2到s1的映射。
同构要求,从s1到s2是一一映射的,不存在一对多的i情况。所以每次查找两个映射都唯一 的情况下就是同构的。
示例源码:
// Len_Somorphic.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <string>
#include <map>
using namespace std;
bool Isomorphic(string s1, string s2)
{
if (s1.size() != s2.size())
{
return false;
}
// 构造两个映射表
map<char, char> myMapSToT;
map<char, char> myMapTToS;
for (int i = 0; i < s1.size(); i++)
{
// s1->t的映射map中查找
if (myMapSToT.find(s1[i]) != myMapSToT.end())
{
if (s2[i] != myMapSToT[s1[i]])
{
return false;
}
}
// s2->s的映射map中查找
else if (myMapTToS.find(s2[i]) != myMapTToS.end())
{
if (s1[i] != myMapTToS[s2[i]])
{
return false;
}
}
else
{
myMapSToT.insert(pair<char, char>(s1[i], s2[i]));
myMapTToS.insert(pair<char, char>(s2[i], s1[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 = "egg";
string s2 = "add";
int nResult = Isomorphic(s1, s2);
PrintString(s1, s2, nResult);
s1 = "foo";
s2 = "bar";
nResult = Isomorphic(s1, s2);
PrintString(s1, s2, nResult);
s1 = "paper";
s2 = "title";
nResult = Isomorphic(s1, s2);
PrintString(s1, s2, nResult);
}
执行结果: