• 205. Isomorphic Strings java solutions


    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.

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

    Subscribe to see which companies asked this question

     
     1 public class Solution {
     2     public boolean isIsomorphic(String s, String t) {
     3         if(s==null || t == null || s.length() != t.length()) return false;
     4         HashMap<Character, Character> hms = new HashMap<Character, Character>();
     5         HashMap<Character, Character> hmt = new HashMap<Character, Character>();
     6         int[] tmp = new int[s.length()];
     7         for(int i = 0; i< s.length();i++){
     8             Character ss = s.charAt(i);
     9             Character tt = t.charAt(i);
    10             if(hms.containsKey(ss) || hmt.containsKey(tt)){
    11                 if(hms.get(ss) != tt || hmt.get(tt) != ss) return false;
    12             }else{
    13                 hms.put(ss,tt);
    14                 hmt.put(tt,ss);
    15             }
    16         }
    17         return true;
    18     }
    19 }

    证明两个字符串是同构的,同个下标的a->b, b->a,即可。

    做法二:

     1 public class Solution {
     2     public boolean isIsomorphic(String s, String t) {
     3         int[] times1 = new int[128], times2 = new int[128];
     4         int len = s.length();
     5         for (int i = 0, smax = 0, tmax = 0; i < len; ++i) {
     6             char sc = s.charAt(i);
     7             char tc = t.charAt(i);
     8             if (times1[sc] == 0) {
     9                 times1[sc] = ++smax;
    10             }
    11             if (times2[tc] == 0) {
    12                 times2[tc] = ++tmax;
    13             }
    14             if (times1[sc] != times2[tc])
    15                 return false;
    16         }
    17         return true;
    18     }
    19 }

    http://blankj.com/404.html

  • 相关阅读:
    lodash chunk
    lodash.slice
    ⚡ vue3 全家桶体验
    构建一个简约博皮的过程
    [译] 制作 Vue 3 的过程
    ⚠ | 不要再使用 markdown 主题了!
    win 常用命令
    2020年了,别再重复学习原型了
    删除 linux 导致原来的 win10 进不去
    手写一个文章目录插件
  • 原文地址:https://www.cnblogs.com/guoguolan/p/5488913.html
Copyright © 2020-2023  润新知