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.
其实这道题和最长子字符串的整体思路有一定的相似,根据ASCII码用只有256个字符,使用两个数组分别记录所出现的字符,类似于一个Hashmap一对一映射的方法,就可以实现两个字符串是否同构的比对。具体实现源码如下:
class Solution{ public: bool isIsomorphic(string s, string t){ int m1[256]={0}; int m2[256]={0}; int n=s.size(); if(t.size()!=s.size()) return false; for(int i = 0;i<n;i++){ if(m1[s[i]]!=m2[s[i]]) return false; m1[s[i]]=i+1; m2[s[i]]=i+1; } } };
浙公网安备 33010602011771号