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;
        }

    优化:

    扩展:

  • 相关阅读:
    动态规划-矩阵链乘法
    钢条切割问题
    代码着色
    Sublime配置C和C++编译运行环境
    Guava中集合类的简单实用
    Junit单元测试入门
    Sublime Text 快捷键
    Editplus 的配色方案
    利用Wireshark任意获取QQ好友IP实施精准定位
    linux下实现定时执行php脚本
  • 原文地址:https://www.cnblogs.com/maydow/p/4642877.html
Copyright © 2011-2022 走看看