zoukankan      html  css  js  c++  java
  • LeetCode(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.

    For example,
    Given “egg”, “add”, return true.

    Given “foo”, “bar”, return false.

    Given “paper”, “title”, return true.

    分析

    判断给定的两个字符串是否同构,字符串字面上很容易就能看得出来;

    但是怎么用算法来判断呢?

    仔细分析:
    e <——> a
    g <——> d
    g <——> d
    感觉像离散数学中的双向映射。

    在数据结构中可以选择map,选择unordered_map来存储字母映射关系,它的搜索性能为常量。

    AC代码

    class Solution {
    public:
        bool isIsomorphic(string s, string t) {
            if (s.size() != t.size())
                return false;
            //求两个字符串的长度
            int len = s.size();
    
            //首先验证字符串s—>t的映射
            unordered_map<char, char> um;
            for (int i = 0; i < len; ++i)
            {
                auto pos = um.find(s[i]);
                if (pos == um.end())
                    um.insert({ s[i], t[i] });
                else{
                    if ((*pos).second != t[i])
                        return false;
                }//else
            }//for
    
            //再验证字符串t—>s的映射
            um.clear();
            for (int i = 0; i < len; ++i)
            {
                auto pos = um.find(t[i]);
                if (pos == um.end())
                    um.insert({ t[i], s[i] });
                else{
                    if ((*pos).second != s[i])
                        return false;
                }//else
            }//for
            return true;
        }
    };

    GitHub测试程序源码

  • 相关阅读:
    浏览器兼容性优化
    js操作table(增加行,删除行,上移,下移,复制行)
    褚时健传读后感
    新鞋
    八达岭奥莱
    springMVC 多方法controller
    springMVC入门配置及helloworld实例
    springMVC源码下载地址
    spring3mvc与struts2比较
    hql语句拼接的替换方式
  • 原文地址:https://www.cnblogs.com/shine-yr/p/5214748.html
Copyright © 2011-2022 走看看