[leedcode 205] 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.

public class Solution {
    public boolean isIsomorphic(String s, String t) {
        //本题需要借助map保存影射信息,如果发现后面的节点和之前影射的不同,直接返回false
        //组要注意的是,主要两个字符影射同一个字符的情况,比如ab  aa,如果使用一个map(正向s->t),此种情况返回的是true,不符合题意
        //因此需要使用两个map,另一个保存反向map(t->s)
        int lens=s.length();
        int lent=t.length();
        if(lens!=lent) return false;
        Map<Character,Character> map=new HashMap<Character,Character>();
        Map<Character,Character> map2=new HashMap<Character,Character>();
        for(int i=0;i<lens;i++){
            char temp=s.charAt(i);
            char te=t.charAt(i);
            if(map.containsKey(temp)){
                if(map.get(temp)!=te) return false;
            }
            if(map2.containsKey(te)){
                if(map2.get(te)!=temp) return false;
            }else{
                map.put(temp,te);
                map2.put(te,temp);
            }
        }
        return true;
    }
}

 

posted @ 2015-08-03 22:29  ~每天进步一点点~  阅读(92)  评论(0编辑  收藏  举报