205. 同构字符串

集合

import java.util.HashMap;

class Solution {
    public boolean isIsomorphic(String s, String t) {

        /**
         * 使用map集合存储字符-字符对应关系,只要有一个不满足就返回false
         */
        HashMap<Character, Character> map = new HashMap<>();

        for (int i = 0; i < s.length(); i++) {

            if (!map.containsKey(s.charAt(i))){

                /**
                 * 不同键的值也不能相等
                 */
                if (map.values().contains(t.charAt(i))){
                    return false;
                }

                map.put(s.charAt(i), t.charAt(i));
            }
            else {

                if (!map.get(s.charAt(i)).equals(t.charAt(i))){
                    return false;
                }
            }
        }

        return true;
    }
}

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(n)
 */

https://leetcode-cn.com/problems/isomorphic-strings/

posted @ 2021-12-01 17:07  振袖秋枫问红叶  阅读(29)  评论(0)    收藏  举报