• LeetCode 205


    一、问题描述

    Description

    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.


    二、解题报告

    所谓的“同构”,就是字符串 s 中的字符可以一对一的映射到字符串 t 中的字符。不能一对多,也不能多对一。

    这里,我的解法是维护两个 map,判断是否是一对一的映射关系:

    // s 和 t 具有相同的长度
    bool isIsomorphic(string s, string t) {
        map<char, char> m1;
        map<char, char> m2;
        bool flag = true;
        for(int i=0; i<s.size(); ++i)
        {
            if(m1.find(s[i])==m1.end() && m2.find(t[i])==m2.end())
            {
                m1[s[i]] = t[i];
                m2[t[i]] = s[i];
            }
            else if(m1.find(s[i])!=m1.end() && m2.find(t[i])!=m2.end())
            {
                if(m1[s[i]]!=t[i] || m2[t[i]]!=s[i])
                {
                    flag = false;
                    break;
                }
            }
            else
            {
                flag = false;
                break;
            }
        }
        return flag;
    }







    LeetCode答案源代码:https://github.com/SongLee24/LeetCode

  • 相关阅读:
    memory addresses
    ddt ddl dml
    PHP Architecture
    disk_free_space
    SAPI
    Simple Mail Transfer Protocol
    AllowOverride None
    function &w(){}
    The History of Operating Systems
    are not called implicitly
  • 原文地址:https://www.cnblogs.com/songlee/p/5738081.html
Copyright © 2020-2023  润新知