[LeetCode] 205 Isomorphic Strings
阿新 • • 發佈:2017-12-24
som ear post inf code clas map 同時 har
原題地址:
https://leetcode.com/problems/isomorphic-strings/description/
題目:
解法一:
記錄s[i]到t[i]的映射,遍歷到與已有的映射不同時,return false。
同樣地,記錄t[i]到s[i]的映射,進行同樣的操作即可。
class Solution { public: bool isIsomorphic(string s, string t) { map<char, char> m; for (int i = 0; i < s.size(); i++) {if (m.find(s[i]) != m.end()) { if (m[s[i]] != t[i]) { return false; } } else { m[s[i]] = t[i]; } } m.clear(); for (int i = 0; i < s.size(); i++) {if (m.find(t[i]) != m.end()) { if (m[t[i]] != s[i]) { return false; } } else { m[t[i]] = s[i]; } } return true; } };
解法二:
bool isIsomorphic(string s, stringt) { int a[256] = {0}, b[256] = {0}; for (int i = 0; i < s.size(); i++) { if (a[s[i]] != b[t[i]]) return false; a[s[i]] = i + 1; b[t[i]] = i + 1; } return true; } };
[LeetCode] 205 Isomorphic Strings