Leetcode 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.

Note:
You may assume both s and t have the same length.


解题思路:

 isomorphic a 同形的,同构的

此题非常类似 Leetcode Word Pattern .

用HashMap, s 里是key, t 里是value. 每次比较,首先检查是否已有该key, 若有,检查对应value 是否相等,不等 return false; 若没有,检查value 是否已存在map里,若有,则two characters may map to the same character, return false, 若没有,put to map.


Java code:

public boolean isIsomorphic(String s, String t) {
        if(s.length() != t.length()){
            return false;
        }
        Map<Character, Character> map = new HashMap<Character, Character>();
        for(int i = 0; i < t.length(); i++) {
            if(map.containsKey(s.charAt(i))){
                if(map.get(s.charAt(i)) != t.charAt(i)){
                    return false;
                }
            }else {
                if(map.containsValue(t.charAt(i))){
                    return false;
                }else {
                    map.put(s.charAt(i), t.charAt(i));
                }
            }
        }
        return true;
    }

 

posted @ 2015-10-10 07:58  茜茜的技术空间  阅读(157)  评论(0编辑  收藏  举报