205. Isomorphic Strings
problem description
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.
Example 1:
Input: s = "egg", t = "add"
Output: trueExample 2:
Input: s = "foo", t = "bar"
Output: falseExample 3:
Input: s = "paper", t = "title"
Output: true
Note:
You may assume both s and t have the same length.algorithm thought
直接用map建立起两个字符串中每个字符之间的映射关系就很好解决
code
class Solution {
public:
    bool isIsomorphic(string s, string t) {
        unordered_map<char,char> ma;
        unordered_set<char> se;
        for(int i=0;i<s.size();++i){
            if(!ma.count(s[i])){
                if(se.count(t[i]))
                    return false;
                ma[s[i]]=t[i];
                se.insert(t[i]);
            }else{
                if(t[i]==ma[s[i]])
                    continue;
                else{
                    return false;
                }
            }
        }
        return true;
    }
};algorithm analysis
一次遍历,时间复杂度O(n),用了map和set保存映射关系,空间复杂度O(n)
Last updated