指尖飞舞

得之坦然,失之淡然,顺其自然,争其必然~~~

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测试程序源码

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fly_yr/article/details/49964999
文章标签: leetcode
个人分类: LeetCode & LintCode
所属专栏: LeetCode & LintCode 题解
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭