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.
Solution in C++: 双向hashtable
class Solution {
public:
bool isIsomorphic(string s, string t) {
if(s.size()!=t.size()) return false;
int idx=0;
map<char, char> mp, rev_mp;
map<char, char>::iterator it;
while(idx<s.size()){
it = mp.find(s[idx]);
if(it!=mp.end()){
char cur = it->second;
if(t[idx]!=cur) return false;
}
else{
it = rev_mp.find(t[idx]);
if(it!=rev_mp.end()) return false;
mp[s[idx]] = t[idx];
rev_mp[t[idx]] = s[idx];
}
idx++;
}
return true;
}
};
字符串匹配:字符映射与等价性判断

本文探讨了如何通过哈希表实现字符串s与字符串t之间的字符映射,判断它们是否具备等价性。通过实例分析,解释了在字符映射规则下,如何确保所有字符的一一对应,且映射关系保持一致性的关键步骤。
349

被折叠的 条评论
为什么被折叠?



