• 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)
  • 相关阅读:
    Ubuntu12.04 亮度调节和保存
    算法
    Python一些常见问题的解决方法
    数据结构
    C# 运行时编译代码并执行 【转】
    C# 动态添加属性 非原创 有修改
    30天学通Visual C++项目案例开发 下載
    .NET常用Request获取信息
    获取一个目录下所有的文件,包括子目录的
    C++入门到精通_全集下载
  • 原文地址:https://www.cnblogs.com/h-hkai/p/9945634.html
Copyright © 2020-2023  润新知