更新时间:2021-08-17 18:50:27
题目概述:
Given two strings s and t, determine if they are isomorphic.我的代码:
bool isIsomorphic(char* s, char* t) { int ls,lt; //字符串长度 int i,j; int nums[256]={0}; int numt[256]={0}; ls = strlen(s); lt = strlen(t); if(ls!=lt) return false; for(i=0; i<ls; i++) { //初值为0 if(nums[s[i]]==0) { if(numt[t[i]]==0) { nums[s[i]] = t[i]; numt[t[i]] = s[i]; } else { return false; } } else { if(nums[s[i]]!=t[i]) { return false; } } } return true; }
C++推荐代码:
参考:http://www.cnblogs.com/easonliu/p/4465650.html
题目很简单,也很容易想到方法,就是记录遍历s的每一个字母,并且记录s[i]到t[i]的映射,当发现与已有的映射不同时,说明无法同构,直接return false。但是这样只能保证从s到t的映射,不能保证从t到s的映射,所以交换s与t的位置再重来一遍上述的遍历就OK了。
class Solution { public: bool isIsomorphic(string s, string t) { if (s.length() != t.length()) return false; map<char, char> mp; for (int i = 0; i < s.length(); ++i) { if (mp.find(s[i]) == mp.end()) mp[s[i]] = t[i]; else if (mp[s[i]] != t[i]) return false; } mp.clear(); for (int i = 0; i < s.length(); ++i) { if (mp.find(t[i]) == mp.end()) mp[t[i]] = s[i]; else if (mp[t[i]] != s[i]) return false; } return true; } };