zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    [背包问题][二进制优化] Jzoj P4224 食物
    [并查集][排序] Jzoj P4223 旅游
    [哈夫曼树][优先队列] Bzoj P4198 荷马史诗
    [hash][差分][虚树] Jzoj P6011 天天爱跑步
    [dp] Jzoj P6012 荷马史诗
    [dp][递归] Jzoj P4211 送你一棵圣诞树
    [数学] Jzoj P3912 超氧化钾
    堆学习笔记(未完待续)(洛谷p1090合并果子)
    [AC自动机]luogu P2444 病毒
    [概率期望][DP]luogu P3830 随机树
  • 原文地址:https://www.cnblogs.com/guoguolan/p/5488913.html
Copyright © 2011-2022 走看看