Idiot-maker

  :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

https://leetcode.com/problems/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.

Example 1:

Input: s = "egg", t = "add"
Output: true

Example 2:

Input: s = "foo", t = "bar"
Output: false

Example 3:

Input: s = "paper", t = "title"
Output: true

解题思路:

需要注意的是,要用两个map。用来处理"ab"->"aa"这种情况。

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

 

posted on 2018-12-28 23:24  NickyYe  阅读(122)  评论(0编辑  收藏  举报