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.

    思路:需要两个方向的映射,从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;
        }

    优化:

    扩展:

  • 相关阅读:
    二分查找算法
    Python基础二(基础数据类型)
    Python基础一
    mysql 数据库
    Scrapy (网络爬虫框架)入门
    列表推导式的使用
    Scrapy(爬虫框架)中,Spider类中parse()方法的工作机制
    vim 基础命令大全
    windows cmd 命令大全
    类与类的关系一
  • 原文地址:https://www.cnblogs.com/maydow/p/4642877.html
Copyright © 2011-2022 走看看