205. Isomorphic Strings

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.

Analysis:
此问题可以分别记录s和t中每个字母对应的对方字符串中的字母,并在每一步做判断。注意,必须双方都做记录,否则像s=”ab”, t=”aa”这样的可能会判断错误。
Source Code(C++):

#include <iostream>
#include <string>
#include <map>
#include <vector>
using namespace std;

/*************************分别逐个判断s和t中每个字符之间的对应关系判断是否出错,注意必须双向判断*************************************/
class Solution {
public:
    bool isIsomorphic(string s, string t) {
        if (s.size() != t.size()) {
            return false;
        }
        map<char, char> ms, mt;
        for (int i=0; i<s.size(); i++) {
            if (ms.find(s.at(i)) != ms.end() || mt.find(t.at(i)) != mt.end()) {
                if (ms[s.at(i)] != t.at(i) || mt[t.at(i)] != s.at(i)) {
                    return false;
                }
            }
            else {
                ms[s.at(i)] = t.at(i);
                mt[t.at(i)] = s.at(i);
            }
        }
        return true;
    }
};


int main() {
    Solution sol;
    cout << sol.isIsomorphic("eb", "ee");
    cout << sol.isIsomorphic("aba", "baa");
    cout << sol.isIsomorphic("abb", "egg");
    return 0;
}

你可能感兴趣的:(205. Isomorphic Strings)