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)
  • 相关阅读:
    RecyclerView的通用适配器
    Service由浅到深——AIDL的使用方式
    Android热修复——Tinker的集成
    ListView ,GridView 通用适配器
    Android开发者必知的5个开源库
    Android下强制打开键盘
    Android下强制打开软键盘
    怎么监听Android软键盘的打开和关闭
    【转】ListView 3D翻页效果
    Android 手动显示和隐藏软键盘
  • 原文地址:https://www.cnblogs.com/h-hkai/p/9945634.html
Copyright © 2011-2022 走看看