您的位置 首页 JAVA(2017)

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;
    }
}
看完了?留个评分呗?
[0人评了分,平均: 0/5]

本站原创文章皆遵循“署名-非商业性使用-相同方式共享 3.0 (CC BY-NC-SA 3.0)”。转载请保留以下标注:

原文来源:《LeetCode – 205. Isomorphic Strings》

发表评论

邮箱地址不会被公开。

返回顶部