zoukankan      html  css  js  c++  java
  • 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;
        }
    }
     
     
  • 相关阅读:
    Django框架之数据库ORM框架
    Django模块之jinja2模版
    Django框架之中间件MiddleWare
    Django框架之类视图
    Django框架之session
    Django框架之cookies
    Django框架之给客户端返回数据
    Django框架之获取客户端发送的数据
    题解 UVA11475 【Extend to Palindrome】
    题解 P3964 【[TJOI2013]松鼠聚会】
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7838853.html
Copyright © 2011-2022 走看看