问题:https://leetcode.com/problems/isomorphic-strings/
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.
分析:两个字符是同构的,说明二者的结构是一样的。对于s中的字符,在t中有且仅有一个相同位置的字符与其相对应。同样对于t,s中有且仅有一个字符与之相对应。用两个容器,来存出现的是哪个字符,以及之前有没有出现过和出现的位置。这两个容器必须每一个对应的值都相等才能说明两个字符同构。
代码:
class Solution {
public:
bool isIsomorphic(string s, string t) {
int l=s.size();
vector<int> v1(256,0);
vector<int> v2(256,0);
for(int i=0;i<l;i++){
if(v1[s[i]] != v2[t[i]])
return false;
v1[s[i]]=i+1;
v2[t[i]]=i+1;
}
return true;
}
};