Given two stringssandt, determine if they are isomorphic.
Two strings are isomorphic if the characters inscan be replaced to gett.
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.
個人覺得挺有意思的一道題。首先要理解到底啥才叫lsomorphic strings。歸納出其的特點。
其實就是字母可以不相同,但是結構必須相同。就是說對于string s,其出現重復字母的index必須和string t,出現重復的字母的index相等而且數量也相同。
搞清楚這個就可以用if statement來寫判斷了。
代碼如下。~
public class Solution { public boolean isIsomorphic(String s, String t) { if(s.length()!=t.length()) return false; HashMap<Character,Integer> smap=new HashMap<>(); HashMap<Character,Integer> tmap=new HashMap<>(); for(int i=0;i<s.length();i++){ if(!smap.containsKey(s.charAt(i))){ if(tmap.containsKey(t.charAt(i))){ return false; } }else{ int index=smap.get(s.charAt(i)); if(!tmap.containsKey(t.charAt(i))||tmap.get(t.charAt(i))!=index){ return false; } } smap.put(s.charAt(i),i); tmap.put(t.charAt(i),i); } return true; }}新聞熱點
疑難解答