205. Isomorphic Strings
Total Accepted: 62899 Total Submissions: 206548 Difficulty: Easy
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.
思路:判断2个字符串是否同构。其实就是映射的问题,如果s和t的字符是一一映射(双射)的关系,就可以说s和t是同构的。
代码:
方法一:将s和t中的字符分别一一映射于整数集合,再对比映射以后的s和t是否相等。
1 class Solution { 2 public: 3 string trans(string s){ 4 int i,m[256]={0}; 5 for(i=0;i<s.size();i++){ 6 if(!m[s[i]]){ 7 m[s[i]]=i+1; 8 } 9 s[i]=m[s[i]]; 10 } 11 return s; 12 } 13 bool isIsomorphic(string s, string t) { 14 if(trans(s)==trans(t)) 15 return true; 16 return false; 17 } 18 };
方法二:
看是否能将s转换为t:
1 class Solution { 2 public: 3 bool isIsomorphic(string s, string t) { 4 char m['z'+1]={0}; 5 bool b['z'+1]={false}; 6 int i; 7 for(i=0;i<s.size();i++){ 8 if(!m[s[i]]&&!b[t[i]]){ 9 m[s[i]]=t[i]; 10 b[t[i]]=true; 11 } 12 if(m[s[i]]==t[i]){ 13 continue; 14 } 15 return false; 16 } 17 return true; 18 } 19 };
方法三:看当前字符最近一次出现的位置是否相等。
1 class Solution { 2 public: 3 bool isIsomorphic(string s, string t) { 4 int m1[256] = {0}, m2[256] = {0}, n = s.size(); 5 for (int i = 0; i < n; ++i) { 6 if (m1[s[i]] != m2[t[i]]) return false; 7 //因为初始值为0,所以要i+1 8 m1[s[i]] = i + 1; //m1记录s[i]在s中最近一次出现的位置 9 m2[t[i]] = i + 1; 10 } 11 return true; 12 } 13 };