205. Isomorphic Strings

Description

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.

Solution

Isomorphic:同构的
要考虑多种case:

  • 1对多:invalid
  • 多对1:invalid
  • 1对1:valid

所以需要注意的地方是,假设a来自s,b来自t:

  • a和b都没有用过:a -> b
  • a用过:检查map.get(a)和b
  • b用过:检查映射到b的是否是a

HashMap, time O(n), space O(n)

class Solution {
    public boolean isIsomorphic(String s, String t) {
        if (s == null || t == null || s.length() != t.length()) {
            return false;
        }
        
        Map<Character, Character> map = new HashMap<>();
        Set<Character> used = new HashSet<>();
        
        for (int i = 0; i < s.length(); ++i) {
            char a = s.charAt(i);
            char b = t.charAt(i);
            
            if (!map.containsKey(a)) {
                if (!used.add(b)) { // don't forget this case!
                    return false;
                }
                map.put(a, b);
            } else if (map.get(a) != b) {
                return false;
            }
        }
        
        return true;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容