【LeetCode】205 Isomorphic Strings(c++実装)

2007 ワード

Given two strings s and t, determine if they are isomorphic.
Two strings are isomorphic if the characters in s can be replaced to gett.
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.
この問題には時間の制限があり、肝心なのはどのように時間を最適化するかです.
私が始めた方法は2つのforループで、時間の複雑さはnの平方ですが、2つの文字列が特に長いテスト例があり、「Time Limit Exceeded」が現れました.コードは次のとおりです.
class Solution {
public: 
    bool isIsomorphic(string s, string t) {
        int len = s.length();//      n  ,       。
        for (size_t i = 0; i < len; i++) {
            for (size_t j = i + 1; j < s.length(); j++) {
                if ((s[i] == s[j] && t[i] != t[j]) || (s[i] != s[j] && t[i] == t[j])) { 
                    return false;
                }
           }
        }
        return true;
    }
};

上記の方法はだめです.それは時間の複雑さを減らさなければなりません.最後に、のmapマッピングを使用して、forループの2つのパラメータの各charを使用して、対応関係が変わったことを発見したら、2つの文字列がisomorphicではないことを説明します.時間複雑度はO(n)であり、コードは以下の通りである.
class Solution {public:bool isIsomorphic(string s, string t) {int len = s.length();
        map<char, char> m;
        map<char, char> m2;for (size_t i = 0; i < len; i++) {if (m.find(s[i]) == m.end()) {
                m[s[i]] = t[i];
            }else if (m[s[i]] != t[i]) {
                return false;
            }if (m2.find(t[i]) == m2.end()) {
                m2[t[i]] = s[i];
            }else if (m2[t[i]] != s[i]) {
                return false;
            }
        }
        return true;
    }
};