zoukankan      html  css  js  c++  java
  • Leetcode 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.

    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.


    解题思路:

     isomorphic a 同形的,同构的

    此题非常类似 Leetcode Word Pattern .

    用HashMap, s 里是key, t 里是value. 每次比较,首先检查是否已有该key, 若有,检查对应value 是否相等,不等 return false; 若没有,检查value 是否已存在map里,若有,则two characters may map to the same character, return false, 若没有,put to map.


    Java code:

    public boolean isIsomorphic(String s, String t) {
            if(s.length() != t.length()){
                return false;
            }
            Map<Character, Character> map = new HashMap<Character, Character>();
            for(int i = 0; i < t.length(); i++) {
                if(map.containsKey(s.charAt(i))){
                    if(map.get(s.charAt(i)) != t.charAt(i)){
                        return false;
                    }
                }else {
                    if(map.containsValue(t.charAt(i))){
                        return false;
                    }else {
                        map.put(s.charAt(i), t.charAt(i));
                    }
                }
            }
            return true;
        }
  • 相关阅读:
    ActiveMQ介绍及安装
    Spring注解驱动开发
    Redis 安装、配置、集群
    FastDFS的使用
    How are you vs How are you doing
    阅微草堂笔记
    我在实习的英文表达
    INTRO: THE DAWN (亡灵序曲) 中独白
    银魂的武士道
    Linguistic Data Consortium (LDC)
  • 原文地址:https://www.cnblogs.com/anne-vista/p/4865670.html
Copyright © 2011-2022 走看看