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.
注意事项
You may assume both s and t have the same length
.
样例
Given s = "egg"
, t = "add"
, return true
.
Given s = "foo"
, t = "bar"
, return false
.
Given s = "paper"
, t = "title"
, return true
.
解题思路:用两个map进行记录,若每个map的值对应全部相等则返回true,否则false。
解题代码:
class Solution {
public:
/**
* @param s a string
* @param t a string
* @return true if the characters in s
* can be replaced to get t or false
*/
bool isIsomorphic(string& s, string& t) {
// Write your code here
if(s.size()!=t.size())return false;
map<char,int>test,comp;
for(int i=0;i<=s.size();i++)test[s[i]]++,comp[t[i]]++;
int flag=0;
for(int i=0;i<=s.size();i++){
if(flag)break;
if(test[s[i]]!=comp[t[i]])flag=1;
}
if(flag)return false;
return true;
}
};