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

    Example 1:

    Input: s = "egg", t = "add"
    Output: true
    

    Example 2:

    Input: s = "foo", t = "bar"
    Output: false

    Example 3:

    Input: s = "paper", t = "title"
    Output: true

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

     

    Approach #1: C++.

    class Solution {
    public:
        bool isIsomorphic(string s, string t) {
            int len = s.size();
            int ArrS[256] = {0};
            int ArrT[256] = {0};
            for (int i = 0; i < len; ++i) {          
                if (charArrS[s[i]] != charArrT[t[i]]) {
                    return false;
                }
                ArrS[s[i]] = i + 1;
                ArrT[t[i]] = i + 1;
            }
            return true;
        }
    };
    

      

    Approach #2: Java.

    class Solution {
    public:
        bool isIsomorphic(string s, string t) {
            int len = s.size();
            int ArrS[256] = {0};
            int ArrT[256] = {0};
            for (int i = 0; i < len; ++i) {          
                if (charArrS[s[i]] != charArrT[t[i]]) {
                    return false;
                }
                ArrS[s[i]] = i + 1;
                ArrT[t[i]] = i + 1;
            }
            return true;
        }
    };
    

      

    Approach #3: Python.

    class Solution(object):
        def isIsomorphic(self, s, t):
            """
            :type s: str
            :type t: str
            :rtype: bool
            """
            arrS = {}
            arrT = {}
            
            for i, val in enumerate(s):
                arrS[val] = arrS.get(val, []) + [i]
                
            for i, val in enumerate(t):
                arrT[val] = arrT.get(val, []) + [i]
            
            return sorted(arrS.values()) == sorted(arrT.values())
    

      

      

    Time SubmittedStatusRuntimeLanguage
    a few seconds ago Accepted 236 ms python
    5 minutes ago Accepted 8 ms java
    13 minutes ago Accepted 4 ms cpp

    Analysis:

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    实现一个基本的静态文件服务的Web服务器
    Http模块
    Java环境
    HelloWorld
    HTTP(s)
    第16条:复合优先于继承
    Tomcat配置https
    第15条:使可变性最小化
    第14条:在公有类中使用访问 方法而非公有域
    第13条:使类和成员的可访问性最小化
  • 原文地址:https://www.cnblogs.com/h-hkai/p/9945634.html
Copyright © 2011-2022 走看看