• [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.

    思路:需要两个方向的映射,从s-t  和从 t-s  。判断之前对应的字符是不是一致,由于存在  “ab” 与“aa”这样的情况,从s到t需要两个映射,而从t到s只需一个映射。

    时间复杂度:O(n)

    代码:

        public boolean isIsomorphic(String s, String t) {
             if(s==null || t==null || s.length()!=t.length()) return false;
             Map<Character, Character> maps=new  HashMap<Character, Character>();
             Map<Character, Character> mapt=new  HashMap<Character, Character>();
             for(int i=0;i<s.length();i++)
             {
                 if(!maps.containsKey(s.charAt(i)))
                     maps.put(s.charAt(i), t.charAt(i));
                 else
                 {
                     if(maps.get(s.charAt(i)).charValue()!=t.charAt(i))
                         return false;
                 }
                 if(!mapt.containsKey(t.charAt(i)))
                     mapt.put(t.charAt(i), s.charAt(i));
                 else 
                 {
                     if(mapt.get(t.charAt(i)).charValue()!=s.charAt(i))
                         return false;                 
                 }
             }
             if(maps.size()!=mapt.size())
                 return false;
             return true;
        }

    优化:

    扩展:

  • 相关阅读:
    2019-04-02 cast and covert
    2019-04-01 为什么零售业务流行起来了?
    2019-04-01 银行的零售业务和对公业务
    服务器推送更新
    webpack 大概
    webpack
    react Hooks
    react 表单受控和非受控
    eslint规则
    react系列笔记:第三记-redux-saga
  • 原文地址:https://www.cnblogs.com/maydow/p/4642877.html
Copyright © 2020-2023  润新知