205. Isomorphic Strings java solutions

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.

 

Subscribe to see which companies asked this question

 
 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         HashMap<Character, Character> hms = new HashMap<Character, Character>();
 5         HashMap<Character, Character> hmt = new HashMap<Character, Character>();
 6         int[] tmp = new int[s.length()];
 7         for(int i = 0; i< s.length();i++){
 8             Character ss = s.charAt(i);
 9             Character tt = t.charAt(i);
10             if(hms.containsKey(ss) || hmt.containsKey(tt)){
11                 if(hms.get(ss) != tt || hmt.get(tt) != ss) return false;
12             }else{
13                 hms.put(ss,tt);
14                 hmt.put(tt,ss);
15             }
16         }
17         return true;
18     }
19 }

证明两个字符串是同构的,同个下标的a->b, b->a,即可。

做法二:

 1 public class Solution {
 2     public boolean isIsomorphic(String s, String t) {
 3         int[] times1 = new int[128], times2 = new int[128];
 4         int len = s.length();
 5         for (int i = 0, smax = 0, tmax = 0; i < len; ++i) {
 6             char sc = s.charAt(i);
 7             char tc = t.charAt(i);
 8             if (times1[sc] == 0) {
 9                 times1[sc] = ++smax;
10             }
11             if (times2[tc] == 0) {
12                 times2[tc] = ++tmax;
13             }
14             if (times1[sc] != times2[tc])
15                 return false;
16         }
17         return true;
18     }
19 }

http://blankj.com/404.html

 

posted @ 2016-05-13 12:03  Miller1991  阅读(165)  评论(0编辑  收藏  举报