LeetCode – 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.

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

这道题一开始没思路,想到之后就很简单

思路:

用两个hash互相映射:

sourceMap[ t[x] ] = s[x]

targetMap[ s[x] ] = t[x]

public class Solution {
    public boolean isIsomorphic(String s, String t) {
        if(s.length() != t.length()) return false;
        HashMap sh = new HashMap();
        HashMap th = new HashMap();
        for(int i=0;i<s.length();i++){
            char sc = s.charAt(i);
            char tc = t.charAt(i);

            if(sh.containsKey(sc)){
                if(!sh.get(sc).equals(tc)){
                    return false;
                }
            }
            else{
                sh.put(sc,tc);
            }
            
            if(th.containsKey(tc)){
                if(!th.get(tc).equals(sc)){
                    return false;
                }
            }
            else{
                th.put(tc,sc);
            }
        }
        return true;
    }
}

邮件订阅,随时获取更新信息

发表评论

电子邮件地址不会被公开。

This site uses Akismet to reduce spam. Learn how your comment data is processed.