【LeetCode】205 Isomorphic Strings (c++實現)
阿新 • • 發佈:2019-02-18
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.
此題目有時間限制,關鍵是如何優化時間。
我開始的做法是兩個for迴圈,那麼時間複雜度就是n的平方,但是它有一個測試用例,兩個字串特別長,於是就出現了“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; } };
上面的方法不行,那就必須要減少時間複雜度,最後我想了一個方法:使用一個<char, char>的map對映,for迴圈兩個入參的每一個char,如果發現對應關係改變了,那麼就說明兩個字串不是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; } };