原题:
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.
Example 1:
Input: s = "egg", t = "add" Output: trueExample 2:
Input: s = "foo", t = "bar" Output: falseExample 3:
Input: s = "paper", t = "title" Output: trueNote:
You may assume both s and t have the same length.
题意是判断string s 和t 的字母一一对应,即是不是满射,应该用哈希表速度快一些,但是空间肯定不是特别理想,结果:
Success
Runtime: 4 ms, faster than 99.72% of C++ online submissions forIsomorphic Strings.
Memory Usage: 9 MB, less than 68.92% of C++ online submissions forIsomorphic Strings.
代码:
class Solution {
public:
bool isIsomorphic(string s, string t) {
char dict1[128]={0};
char dict2[128]={0};
memset(dict1,128,0);
memset(dict2,128,0);
for(int i=0;i<t.size();i++){
if(dict1[s[i]]==0&&dict2[t[i]]==0){dict1[s[i]]=t[i];dict2[t[i]]=s[i];continue;}
else if(dict1[s[i]]!=t[i]||dict2[t[i]]!=s[i]){return false;}
}
return true;
}
};