[LeetCode] Isomorphic Strings

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.

Note:
You may assume both s and t have the same length.

解题思路:

这道题是判断两个单词是否同构。这里的同构的意思是,对于例子egg和add,若存在一个映射,e->a,g->d,单词egg和add同构。注意,不可以多个字符映射到同一个字符中去,比如aa和ab。因此要有两个hash表来记录。由于是字符,不会超过256个,因此可以用数组来记录这种映射。

class Solution {
public:
    bool isIsomorphic(string s, string t) {
        int len1=s.length();
        int len2=t.length();
        if(len1!=len2){
            return false;
        }
        char charMap[256];
        char charMap1[256];
        memset(charMap, 0, sizeof(char)*256);
        memset(charMap1, 0, sizeof(char)*256);
        for(int i=0; i<len1; i++){
            if(charMap[s[i]]==0){
                charMap[s[i]] = t[i];
            }else if(charMap[s[i]]!=t[i]){
                return false;
            }
            if(charMap1[t[i]]==0){
                charMap1[t[i]] = s[i];
            }else if(charMap1[t[i]]!=s[i]){
                return false;
            }
        }
        return true;
    }
};


0 条评论

    发表评论

    电子邮件地址不会被公开。 必填项已用 * 标注