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.
思路:利用ascii码,每个字符对应0~255的值,例如'A'的ascii值为65,'a'为97.将字符串s和t中的所有字符分别映射到长度为256的表vs和vt中,则所有256种可能的字符在映射表中都有且仅有唯一的位置(即数组下标).
此外,若s和t是同构字符串,则最多只存在256种对应关系,用一个唯一的整数表示这种唯一的对应关系,充当这个匹配的"桥梁"(自行体会).
//复杂度O(n)
class Solution {
public:
bool isIsomorphic(string s, string t) {
vector vs(256, -1);//映射表,全部初始化为-1
vector vt(256, -1);
for(int i = 0; i < s.length(); i++){//一次遍历字符串
if(vs[s[i]] != vt[t[i]]){//若i处的两个字符映射关系不匹配,则错误
return false;
}
vs[s[i]] = i;//否则将i处字符的ascii值做为两个映射表的下标,并填入i以表示这对匹配关系
vt[t[i]] = i;
}
return true;
}
};
https://leetcode.com/problems/isomorphic-strings/description/
http://www.cnblogs.com/aprilcheny/p/4929679.html