您的位置:首页 > 其它

同构字符串

2015-08-06 22:02 218 查看

题目

Given two strings s and t, determine if they are isomorphic.

Two strings are isomorphic if the characters in s can be replaced to get t.

All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.

For example,

Given “egg”, “add”, return true.

Given “foo”, “bar”, return false.

Given “paper”, “title”, return true.

Note:

You may assume both s and t have the same length.

翻译

给定两个字符串s and t,判断它们是否是同构字符串。

同构字符串是指,s 中的字符可以被替换以得到 t

字符串中同一个字符的所有出现位置必须被相同的字符替换,并且不改变其在原始字符串中的位置。不同的字符不能够被映射到相同的字符,但是一个字符可以映射到本身,例:

a , a

“egg”, “add”,

“foo”, “bar”,

“paper”, “title”,

我的解决办法是:通过hashMap构造st以及ts的映射,然后在加上条件判断即可。代码如下(代码假设st等长):

bool isIsomorphic(string s, string t) {
int aTob[256] = {0};//s到t的映射
int bToa[256] = {0};//t到s的映射
size_t len = s.size();

for(size_t i =0; i<len; ++i)
{
if(aTob[s[i]] == 0)
aTob[s[i]] = t[i];//初始化aTob
if(bToa[t[i]] == 0)
bToa[t[i]] = s[i];//初始化bToa
if(aTob[s[i]] != t[i] ||
bToa[t[i]] != s[i])
return false;
}
return true;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: