205.同构字符串
题目链接
205. 同构字符串 - 力扣(LeetCode)
完整代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| class Solution { public: bool isIsomorphic(string s, string t) { string ss; string st; int hash[255]; int index=0; memset(hash, 0, sizeof(hash)); for(int i=0;i<s.size();i++){ if(hash[int(s[i])]==0) { index++; hash[int(s[i])]=index; ss.push_back(index+'0'); }else{ ss.push_back(hash[int(s[i])]+'0'); } } index=0; memset(hash, 0, sizeof(hash)); for(int i=0;i<t.size();i++){ if(hash[int(t[i])]==0) { index++; hash[int(t[i])]=index; st.push_back(index+'0'); }else{ st.push_back(hash[int(t[i])]+'0'); } } int ans = ss.compare(st); if(ans==0){ return true; }else{ return false; } return true; } };
|
参考代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| class Solution { public: bool isIsomorphic(string s, string t) { unordered_map<char, char> s2t; unordered_map<char, char> t2s; int len = s.length(); for (int i = 0; i < len; ++i) { char x = s[i], y = t[i]; if ((s2t.count(x) && s2t[x] != y) || (t2s.count(y) && t2s[y] != x)) { return false; } s2t[x] = y; t2s[y] = x; } return true; } };
|
参考链接
同构字符串 - 同构字符串 - 力扣(LeetCode)