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

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


     题目标签:Hash Table

      题目给了我们两个string, 让我们判断它们是不是isomorphic。

      只有当两个string的 char 是 1对1 map的时候,才是isomorphic,那么来看一下两个情况,它们不是 1对1 map:

        1. bar  foo

         map: 

          b -> f

          a -> o

          r  ->   

          这种情况就是 左边两个chars  map 到了 同一个 右边的 char;

        2. bb  fa

         map:

          b -> f

          b -> a

          这种情况就是 右边两个chars map 到了 同一个 左边的char;

      所以只要遇到这两种情况,返回false,剩下的就是true。

    Java Solution:

    Runtime beats 57.23% 

    完成日期:05/26/2017

    关键词:HashMap

    关键点:利用HashMap来记录1对1map

     1 class Solution 
     2 {
     3     public boolean isIsomorphic(String s, String t) 
     4     {
     5         HashMap<Character, Character> map = new HashMap<>();
     6         
     7         for(int i=0; i<s.length(); i++)
     8         {
     9             char sChar = s.charAt(i);
    10             char tChar = t.charAt(i);
    11             
    12             if(map.containsKey(sChar)) 
    13             {
    14                 if(!map.get(sChar).equals(tChar)) // case 1: two different right chars map to one left char
    15                     return false;
    16             }
    17             else
    18             {   
    19                 if(map.containsValue(tChar)) // case 2: two different left chars map to one right char
    20                     return false;
    21                 
    22                 map.put(sChar, tChar);    
    23             }
    24           
    25         }
    26         
    27         return true;
    28     }
    29 }

    参考资料:N/A

    LeetCode 题目列表 - LeetCode Questions List

  • 相关阅读:
    【Linux】- 文件基本属性
    【Linux】- mv命令
    【Linux】- 守护进程supervisor安装使用
    【Linux】- rm命令
    【Linux】- 开启远程连接
    【Redis】- 安装为windows服务
    Apache2.4 与 php7.1.6的链接
    apache2.4 的安装
    MySQL v5.7.18 版本解压安装
    网站系统消息表设计
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/7742411.html
Copyright © 2011-2022 走看看