Isomorphic Strings

Given two strings s and t, determine if they are isomorphic.spa

Two strings are isomorphic if the characters in s can be replaced to get t.code

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.blog

For example,
Given "egg""add", return true.字符串

Given "foo""bar", return false.get

Given "paper""title", return true.string

題意:hash

給定兩個字符串s和t,判斷它們是不是同構的。it

若是字符串s能夠經過字符替換的方式獲得字符串t,則稱s和t是同構的。io

字符的每一次出現都必須被其對應字符所替換,同時還須要保證原始順序不發生改變。兩個字符不能映射到同一個字符,可是字符能夠映射到其自己。class

假設s和t等長。

 

思路:

用兩個hash維護s與t的一一映射關係

 

 1 class Solution {
 2 public:
 3     bool isIsomorphic(string s, string t) {
 4         if (s.empty() && t.empty()) {
 5             return true;
 6         }
 7         if (s.empty() || t.empty()) {
 8             return false;   
 9         }
10         unordered_map<char, char> map_s2t;
11         unordered_map<char, char> map_t2s;
12         
13         for (int i = 0; i < s.size(); i++) {
14             if (map_s2t.find(s[i]) != map_s2t.end()) {
15                 if (map_s2t[s[i]] != t[i]) {
16                     return false;
17                 }
18             }
19             
20             if (map_t2s.find(t[i]) != map_t2s.end()) {
21                 if (map_t2s[t[i]] != s[i]) {
22                     return false;
23                 }
24             }
25             
26             map_s2t[s[i]] = t[i];
27             map_t2s[t[i]] = s[i];
28         }
29         return true;
30     }
31 };
相關文章
相關標籤/搜索