码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Isomorphic Strings

时间:2017-10-07 18:39:21      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:ret   res   构建   can   min   code   ++   solution   div   

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.

判断两个字符串是否同构。

同构的条件是字符串s和t中对位的字母是否存在某种唯一的映射关系。

所以利用两个map来构建映射关系,ms来构建s->t的映射关系。mt来构建t->s的映射关系。在同一对位字母下,ms与mt的键值正好相反。

判断如果与已经存在的键值不匹配,则返回false即可

class Solution {
public:
    bool isIsomorphic(string s, string t) {
        unordered_map<char, char> ms;
        unordered_map<char, char> mt;
        for (int i = 0; i != s.size(); i++) {
            if (ms[s[i]] == 0 && mt[t[i]] == 0) {
                ms[s[i]] = t[i];
                mt[t[i]] = s[i];
            }
            else if (ms[s[i]] != t[i] || mt[t[i]] != s[i])
                return false;
        }
        return true;
    }
};
// 9 ms

 

[LeetCode] Isomorphic Strings

标签:ret   res   构建   can   min   code   ++   solution   div   

原文地址:http://www.cnblogs.com/immjc/p/7635137.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!