PROBLEM:
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.
SOLVE:
class Solution {
public:
bool isIsomorphic(string s,string t){
int n=s.size();
int index[2][256]={0};
for(int i=0;i<n;i++){
if(index[0][s[i]]!=index[1][t[i]])
return false;
index[0][s[i]]=i+1;
index[1][t[i]]=i+1;
}
return true;
}
};
分析:s和t同时遍历,同时判断s或t在之前有没有出现过,如果都出现过且出现的位置相同则ok;否则就输出false。