美文网首页
205. Isomorphic Strings

205. Isomorphic Strings

作者: yunmengze | 来源:发表于2018-10-01 00:18 被阅读0次

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 s and t have the same length.


这道题可以使用一个哈希表来存储已遍历的配对,用一个集合来保存被配对的字符,如果出现字符串s和t中相应的字符对不在哈希表中或者被配对的字符在集合中已经出现过,则认为这两个字符串不是同构字符串。

class Solution {
public:
    bool isIsomorphic(string s, string t) {
        int len1 = s.size();
        int len2 = t.size();
        if(len1 != len2)
            return false;
        unordered_map<int, int> characterMap;
        set<int> data;
        for(int i=0;i<len1;i++){
            if(characterMap.find(s[i]) != characterMap.end()){
                if(characterMap[s[i]] != t[i])
                    return false;
            }
            else{
                if(data.find(t[i]) != data.end())
                    return false;
                characterMap[s[i]] = t[i];
                data.insert(t[i]);
            }
        }
        return true;
    }
};

相关文章

  • 205. Isomorphic Strings

    205. Isomorphic Strings 题目:https://leetcode.com/problems/...

  • 2019-01-21

    LeetCode 205. Isomorphic Strings Description Given two st...

  • 205. Isomorphic Strings

    https://leetcode.com/problems/isomorphic-strings/descript...

  • 205. Isomorphic Strings

    Problem Given two strings s and t, determine if they are ...

  • 205. Isomorphic Strings

    竟然这样ac了,我只是试了一下。。。想法就是对于每一个字符串都建立一个哈希表,统计他们各个字母的数量,对于相同位置...

  • 205. Isomorphic Strings

    题目分析 原题链接,登录 LeetCode 后可用这道题目让我们判断两个字符串是否是同构字符串。示例如下: 解题思...

  • 205. Isomorphic Strings

    Given two strings s and t, determine if they are isomorph...

  • 205. Isomorphic Strings

    Given two stringssandt, determine if they are isomorphic....

  • 205. Isomorphic Strings

    首先考虑corner case,这题两个空字符返回算True…… 从左到右扫,映射关系存为字典。 如果左边扫到重复...

  • 205. Isomorphic Strings

    问题 Given two strings s and t, determine if they are isomo...

网友评论

      本文标题:205. Isomorphic Strings

      本文链接:https://www.haomeiwen.com/subject/flvgoftx.html