zoukankan      html  css  js  c++  java
  • [LeetCode]51. Ismorphic 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.

    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.

    解法:同构字符串,就是说原字符串中的每个字符可由另外一个字符替代,可以被其本身替代,相同的字符一定要被同一个字符替代,且一个字符不能被多个字符替代,即不能出现一对多的映射。需要考虑两种情况:t中的相同字符映射到s中后是不同的字符("aa"-->"ab");t中的不同字符映射到s中后是相同的字符("ab"-->"aa")。因此设置两个Map,一个为t在s中的映射,另一个是s在t中的映射。后者是为了检查上面所说第二种情况。

    class Solution {
    public:
        bool isIsomorphic(string s, string t) {
            int n = s.size();
            vector<int> vt(256, -1); //t中字符在s中的映射
            vector<int> vs(256, -1); //s中字符在t中的映射
            for(int i = 0; i < n; ++i)
            {
                if(vt[t[i]] == -1) //t中当前字符还未映射过
                {
                    if(vs[s[i]] == -1) //s中当前字符还未被映射过
                    {
                        vt[t[i]] = s[i];
                        vs[s[i]] = t[i];
                    }
                    else if(vs[s[i]] != t[i]) return false; //two characters map to the same character
                }
                else if(s[i] != vt[t[i]]) return false; //a character map to two characters
            }
            return true;
        }
    };

    一种更简便的办法是:如果找到一对新的映射(s和t中的对应字符还没出现过),则将两个映射表的相应位置设为同一值,否则判断两个映射表的值是否相同即可。

    class Solution {
    public:
        bool isIsomorphic(string s, string t) {
            int n = s.size();
            vector<int> vt(256, -1); //t中字符在s中的映射
            vector<int> vs(256, -1); //s中字符在t中的映射
            for(int i = 0; i < n; ++i)
            {
                //t的当前字符已经在s中映射过或者s的当前字符已经在t中映射过,并且当前的映射和之前的映射不一致
                if(vt[t[i]] != vs[s[i]]) return false;
                //找到一对全新的映射
                vt[t[i]] = i;
                vs[s[i]] = i;
            }
            return true;
        }
    };
  • 相关阅读:
    行列式运算法则
    神经元的数学模型
    Neural Network and Artificial Neural Network
    常见的23种设计模式
    Java 基本数据类型 及 == 与 equals 方法的区别
    MySQL经典编程问题
    MyEclipse配置tomcat报错
    MySQL 日期类型函数及使用
    MySQL dump文件导入
    MySQL 的两个特殊属性 unsigned与 zerofill
  • 原文地址:https://www.cnblogs.com/aprilcheny/p/4929679.html
Copyright © 2011-2022 走看看