Isomorphic Strings

Given two strings s and t, determine if they are isomorphic.spa

Two strings are isomorphic if the characters in s can be replaced to get t.code

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.blog

For example,
Given "egg""add", return true.get

Given "foo""bar", return false.string

Given "paper""title", return true.it

Note:
You may assume both s and t have the same length.io

 

 

 1 public class Solution {
 2     public boolean isIsomorphic(String s, String t) {
 3         if(s == null || t == null || s.length() != t.length()) return false;
 4         int len = s.length();
 5         HashMap<Character, Character> sTot = new HashMap<Character, Character> ();
 6         HashMap<Character, Character> tTos = new HashMap<Character, Character> ();
 7         for(int i = 0; i < len; i ++){
 8             char sc = s.charAt(i);
 9             char tc = t.charAt(i);
10             if(!sTot.containsKey(sc)){ 
11                 sTot.put(sc, tc);
12             }else{
13                 if(sTot.get(sc) != tc) return false;
14             }
15             //take care case: ab & aa
16             if(!tTos.containsKey(tc)){
17                 tTos.put(tc, sc);
18             }else{
19                 if(tTos.get(tc) != sc) return false;
20             }
21         }
22         return true;
23     }
24 }
相關文章
相關標籤/搜索