leetcode - Isomorphic Strings
leetcode - 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.
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.
1 class Solution { 2 public: 3 bool isIsomorphic(string s, string t) { 4 int sHashtable[256]={0}; 5 int tHashtable[256]={0}; 6 int len = s.size(); 7 for(int i=0; i<len; i++){ 8 if(sHashtable[s[i]]==0){ 9 if(tHashtable[t[i]]==0){ 10 sHashtable[s[i]]=t[i]; 11 tHashtable[t[i]]=s[i]; 12 } 13 else return 0; 14 } 15 else 16 if(sHashtable[s[i]]!=t[i]) return 0;//same char map to different chars 17 } 18 return 1; 19 } 20 };
题目的标签是hashtable,一开始我想用简单的方法,以为只有24个字母,所以就把每个字母的映射存下来。但是后来发现,不仅仅有字母,还有数字,所以24维的数组肯定不行。另外不仅要保证同样的字母映射到同样的字母,还要保证不同的字母不能映射到一样的字母。
参考了别人的写法。 思路是建立256维数组(因为最多有256个ascii码?),然后建立两个hash表。开始遍历,如果string
s 中出现新字符,要确保映射t也是新的。如果s中是以前出现过的,那么就要验证其映射是否和以前一样。
(其实第二个hashtable 只是一个flag,用于验证是否出现过了)
fighting……