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

    优化:

    扩展:

  • 相关阅读:
    nginx服务与nfs服务
    linux基础(3)
    Linux基础(4)
    Linux命令基础(2)
    Linux命令基础(1)
    HTML——表单验证、正则表达式、事件
    css修改鼠标指针的形状
    ajax请求tab切换重新渲染Echarts图表
    5种状态下的HTTP状态码
    vue&Angular&React的优缺点
  • 原文地址:https://www.cnblogs.com/maydow/p/4642877.html
Copyright © 2020-2023  润新知