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.

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

Given "foo""bar", return false.

Given "paper""title", return true.

 

判断2个字符串是否同构,思路:可先将字符串转换成abc的形式,若同构则转换后的字符串应该相等,代码如下:

public class Solution {
    
    /**
     * 将字符串转换成abc的形式如egg->abb,paper->abacd
     */
    public String transform(String s) {
        StringBuffer re = new StringBuffer("");
        char tmp = 'a';
        Map<Character,Character> map = new HashMap<Character,Character>();
        for(int i=0;i<s.length();i++) {
            if(!map.containsKey(s.charAt(i))) {
                map.put(s.charAt(i),tmp);
                re.append(tmp);
                tmp++;
            }
            else {
                re.append(map.get(s.charAt(i)));
            }
        }
        return re.toString();
    }
    
    public boolean isIsomorphic(String s, String t) {
        if(transform(s).equals(transform(t))) return true;
        else return false;
    }
}

 

posted @ 2015-04-29 10:29  mrpod2g  阅读(369)  评论(0编辑  收藏  举报