首页 > 其他 > 详细

Isomorphic Strings

时间:2015-05-05 15:56:21      阅读:303      评论:0      收藏:0      [点我收藏+]

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

Isomorphic Strings

原文:http://www.cnblogs.com/sunshisonghit/p/4479185.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!