美文网首页
LeetCode 205 Isomorphic Strings

LeetCode 205 Isomorphic Strings

作者: ShuiLocked | 来源:发表于2016-08-01 22:01 被阅读193次

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.

判断两个字符串是否同构,要点在于,字符串S1与S2中的字符只能一一对应,如果用两个map记录相互对应关系,S1中的字符a对应S2中的字符b可以表示为map1:<a,b>与map2:<b,a>,当S1再次出现a时,S2对应位置一定是map1中的b;而当S1中出现c时,map2中一定不含有key:c。

代码如下:

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

相关文章

网友评论

      本文标题:LeetCode 205 Isomorphic Strings

      本文链接:https://www.haomeiwen.com/subject/zshfsttx.html