Isomorphic Strings

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.

思路:

  读懂题意后,简单的映射问题而已 Hashmap

我的代码:

public class Solution {
    public boolean isIsomorphic(String s, String t) {
        if(s==null && t==null)  return true;
        if(s==null || t==null || s.length()!=t.length())    return false;
        int len = s.length();
        HashMap<Character,Character> oneToTwo = new HashMap<Character,Character>();
        HashMap<Character,Character> twoToOne = new HashMap<Character,Character>();
        
        for(int i=0; i<len; i++)
        {
            char a = s.charAt(i);
            char b = t.charAt(i);
            if(oneToTwo.containsKey(a))
            {
                char tmp = oneToTwo.get(a);
                if(b != tmp)    return false;
            }
            else
                oneToTwo.put(a, b);
            if(twoToOne.containsKey(b))
            {
                char tmp = twoToOne.get(b);
                if(a != tmp)    return false;
            }
            else
                twoToOne.put(b, a);
        }
        return true;
    }
}
View Code

他人代码:

public class Solution {
    public boolean isIsomorphic(String s, String t) {
        char[] map1 = new char[256], map2 = new char[256];
        for (int i = 0; i < s.length(); i++) {
            char a = s.charAt(i);
            char b = t.charAt(i);
            if (!this.map(a, b, map1) || !this.map(b, a, map2)) { return false; }
        }
        return true;
    }

    private boolean map(char a, char b, char[] map) {
        if (map[a] == 0) { map[a] = b; }
        return map[a] == b;
    }
}
View Code

学习之处:

  对于char类型的hashmap问题,为什么为什么不用数组非得用hashmap呢,下次应该注意常用char数组,而非hashmap

posted on 2015-05-05 15:04  zhouzhou0615  阅读(169)  评论(0编辑  收藏  举报

导航