letecode [205] - 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.
Example 1:
Input: s ="egg",t ="add"Output: true
Example 2:
Input: s ="foo",t ="bar"Output: false
Example 3:
Input: s ="paper",t ="title"Output: true
题目大意:
判断两个字符串是否同构,若两字符串间的字符可以唯一映射,则同构。
理 解:
方法一:辅助空间
用map保存映射关系。若s[i]出现在map中,则判断当前映射是不是s[i]->t[i],不是则返回false。
若不在map中,判断t[i]是否已被其他字符映射(保存在set中),若已被映射,则为false。
其他情况,往后比较其余字符。
方法二:直接判断
这是其他人的方法,判断相同字符串是否在相同的位置出现。
以s[i]为依据,若s[i]==s[j],则理应t[i]==t[j]才满足映射。
代 码 C++:方法一:
class Solution { public: bool isIsomorphic(string s, string t) { int i; map<char,char> m; map<char,char>::iterator it; set<char> st; i = 0; while(s[i]!='\0'){ it = m.find(s[i]); if(it == m.end()){ if(st.count(t[i])==1) return false; m.insert(pair(s[i],t[i])); st.insert(t[i]); }else{ if(it->second == t[i]){ ++i; }else{ return false; } } } return true; } };
方法二:
class Solution { public: bool isIsomorphic(string s, string t) { if(s.size()!=t.size()) return false; for(int i=0;i<s.size();i++) { //直接过滤后面相同的字符 if(s.find(s[i])!=t.find(t[i])) return false; } return true; } };
运行结果:
方法一:执行用时 :16 ms, 在所有C++提交中击败了73.23%的用户
内存消耗 :9.2 MB, 在所有C++提交中击败了23.89%的用户
方法二:执行用时 :12 ms, 在所有C++提交中击败了94.03%的用户
内存消耗 :9 MB, 在所有C++提交中击败了51.99%的用户

浙公网安备 33010602011771号