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

    Example 1:

    Input: s = "egg", t = "add"
    Output: true
    

    Example 2:

    Input: s = "foo", t = "bar"
    Output: false

    Example 3:

    Input: s = "paper", t = "title"
    Output: true

    Note:
    You may assume both and have the same length.

    class Solution {
        public boolean isIsomorphic(String s, String t) {
            HashMap<Character, Character> map1 = new HashMap<>();
            HashMap<Character, Character> map2 = new HashMap<>();
            for(int i = 0; i < s.length(); i++){
               char c1 = s.charAt(i);
               char c2 = t.charAt(i);
                if(map1.containsKey(c1)){
                    if(map1.get(c1) != c2){
                        return false;
                    }
                }
                else {
                    map1.put(c1, c2);
                }
                if(map2.containsKey(c2)){
                    if(map2.get(c2) != c1){
                        return false;
                    }
                }
                else {
                    map2.put(c2, c1);
                }
            }
            return true;
        }
    }

    判断两个string是否同构

    abb 和 egg同构

    ab和aa 不同构
    用两个hashmap来存放对应的char。不同构本质上是因为有一个字母对应不上,意思就是对应不上之前已经有的结构,比如aa和ab,aa已经对应了,那剩下有a出现只能也对应a,所以ab就不同构了。

  • 相关阅读:
    Git with SVN 协同设定
    Apache+Django+mod_wsgi安装目录
    ROR study
    PHP框架
    Gerrit 配置
    Garmin、任我游品牌自制等高线方法比较
    使用python发送outlook约会提醒邮件
    Apache部署多个django site project
    Aptana Studio 3安装(Windows)
    The Art of Readable Code
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11406647.html
Copyright © 2011-2022 走看看