• 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.

    解题思路:

    可以用一个hash map来记录该字母上一次出现的位置。

    若s和t为同构:

      1.若s中i位置的字母第一次出现,那么t中i位置的字母也应当第一次出现。

      2.若s中i位置的字母不是第一次出现,那么t中i位置的字母的上一次出现的位置应当与s[i]上一次出现的位置相同。

    代码:

    class Solution {
    public:
        bool isIsomorphic(string s, string t) {
            unordered_map<char, int> m_s;
            unordered_map<char, int> m_t;
            for(int i = 0; i < s.size(); i++){
                if(m_s.count(s[i]) ^ m_t.count(t[i])) return false;
                else{
                    if(m_s.count(s[i])){
                        if(m_s[s[i]] != m_t[t[i]]) return false;
                    }
                    m_s[s[i]] = i;
                    m_t[t[i]] = i;
                }
            }
            return true;
        }
    };
  • 相关阅读:
    c语言数组指针
    (4)activiti工作流引擎之uel表达式
    (3)activiti流程的挂起和激活
    (2)java程序走一遍工作流activiti
    (1)activiti认识以及数据库和插件配置
    linux 下路由配置
    lvs-dr+keepalived
    LVS-DR 配置测试
    简单认识TCP/IP协议
    mysql 主从同步-读写分离
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9393827.html
Copyright © 2020-2023  润新知