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和t,判断它们是否是同构的。
如果字符串s可以通过字符替换的方式得到字符串t,则称s和t是同构的。
字符的每一次出现都必须被其对应字符所替换,同时还需要保证原始顺序不发生改变。两个字符不能映射到同一个字符,但是字符可以映射到其本身。
假设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 };
时间: 2024-10-08 17:09:21