205-Ismorphics 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个字符串s和t,判断他们是否是同构。

  如果在s中的所有字符可以被t中的字符替换,则两个字符串是同构的。

  所有出现的字符必须被另一个字符替换,没有2个字符可以映射到同一个字符上

  举例

  给 "egg" , "add" , return true.

  给 "foo" , "bar" , return false.

  给 "paper" , "title" , return true.

【分析】

  1. 将两个字符串的字符映射到map上

【算法实现】

public class Solution {
    public boolean isIsomorphic(String s, String t) {
        Map<Character,Character> map = new HashMap<Character,Character>();
        //Map<Character,Character> map2 = new HashMap<Character,Character>();
        char[] cs = s.toCharArray();
        char[] ts = t.toCharArray();
        int len = cs.length;
        for(int i=0; i<len; i++) {
            if(map.containsKey(cs[i])) {
                if(map.get(cs[i])!=ts[i])
                    return false;
            }else if(map.containsValue(ts[i])){
                return false;
            }else {
                map.put(cs[i], ts[i]);
            }
        }
        return true;
    }
}

 

posted @ 2015-05-21 17:34  hwu_harry  阅读(153)  评论(0编辑  收藏  举报