[LeetCode] Isomorphic Strings, leetcodeisomorphic
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.
I personally think this is an interesting question. First, you must understand what it is called lsomorphic strings. Summarize its features.
In fact, the letters can be different, but the structure must be the same. That is to say, for string s, the index of the duplicate letter must be the same as the string t, and the index of the duplicate letter must be the same and the number is the same.
You can use if statement to write and judge the statement.
The Code is as follows .~
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; }}