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

  • 相关阅读:
    【Python之路】第三篇--Python基本数据类型
    【Python之路】第二篇--初识Python
    【Python之路】第一篇--Linux基础命令
    noip模拟测试7
    noip模拟测试6
    动态添加select的option [转载]
    javaweb报错:java.lang.NumberFormatException: null
    Javascript获取select的选中值和选中文本(转载)
    动态生成select框内容
    IO(Input&Output)流の介绍
  • 原文地址:https://www.cnblogs.com/guoguolan/p/5488913.html
Copyright © 2011-2022 走看看