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.
Note:
You may assume both s and t have the same length.
思路: 注意本题是一一对应的关系,而hashmap只能保证索引值唯一,即s到t是唯一的,但是可能存在2个s对应同一个t,所以增加了set加以判断
class Solution { public: bool isIsomorphic(string s, string t) { int len = s.length(); if(len == 0) return true; map<char,char> c_map; set<char> c_set; //to avoid two character in s maps to the same character in t for(int i = 0; i < len; i++){ if(c_map.find(s[i]) == c_map.end()){ if(c_set.find(t[i]) == c_set.end()){ c_map[s[i]] = t[i]; c_set.insert(t[i]); } else return false; } else if(c_map[s[i]]!=t[i]) return false; } return true; } };
时间: 2024-12-28 13:34:24