[LeetCode] 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.

題目很簡單,也很容易想到方法,就是記錄遍歷s的每一個字母,並且記錄s[i]到t[i]的映射,當發現與已有的映射不同時,說明無法同構,直接return false。但是這樣只能保證從s到t的映射,不能保證從t到s的映射,所以交換s與t的位置再重來一遍上述的遍歷就OK了。

 1 class Solution {
 2 public:
 3     bool isIsomorphic(string s, string t) {
 4         if (s.length() != t.length()) return false;
 5         map<char, char> mp;
 6         for (int i = 0; i < s.length(); ++i) {
 7             if (mp.find(s[i]) == mp.end()) mp[s[i]] = t[i];
 8             else if (mp[s[i]] != t[i]) return false;
 9         }
10         mp.clear();
11         for (int i = 0; i < s.length(); ++i) {
12             if (mp.find(t[i]) == mp.end()) mp[t[i]] = s[i];
13             else if (mp[t[i]] != s[i]) return false;
14         }
15         return true;
16     }
17 };

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM