• leetcode205- Isomorphic Strings- easy


    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.

    用两个hashMap,分别表示s到t的字符映射和t到s的字符映射。如果出现了和以前的映射不匹配的情况,那就是不行的。

    细节:1.两者长度不同的corner case 2.char的比较也要用equals不能用== 3.小心要两个hashmap,一个不够的比如"aa","ab"

    实现:

    class Solution {
        public boolean isIsomorphic(String s, String t) {
            
            if (s == null || t == null || s.length() != t.length()) {
                return false;
            }
            Map<Character, Character> mapA = new HashMap<>();
            Map<Character, Character> mapB = new HashMap<>();
            for (int i = 0; i < s.length(); i++) {
                Character sc = s.charAt(i);
                Character tc = t.charAt(i);
                if (mapA.containsKey(sc) && !mapA.get(sc).equals(tc) || mapB.containsKey(tc) && !mapB.get(tc).equals(sc)) {
                    return false;
                }
                mapA.put(sc, tc);
                mapB.put(tc, sc);
            }
            return true;
        }
    }
     
     
  • 相关阅读:
    GRIDVIEW导出到EXCEL
    数据表示:字节 高位低位
    js学习笔记0
    12奇招,循序删除顽固的文件
    加快开关机速度
    PHP正则表达式的快速学习
    firefox下height不能自动撑开的解决办法
    给MySQL加密(也适用于Wamp5中)
    我的电脑创建资源管理器
    css 圆角7种CSS圆角框解决方案
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7838853.html
Copyright © 2020-2023  润新知