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.

    解题思路:

    可以用一个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;
        }
    };
  • 相关阅读:
    纪念我用word发布的第一篇文章
    第一个SpringMVCHelloWorld
    JSTL学习笔记
    bonecp的使用
    hdu 1556 树状数组
    hdu 1561 树形DP
    MYSQL使用笔记
    Android中简单实现Spinner的数据绑定
    Android中利用Application实现多个Activity间共享数据
    技术到底重要不重要?
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9393827.html
Copyright © 2011-2022 走看看