leetcode@ [205] Isomorphic Strings

https://leetcode.com/problems/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.

 

class Solution {
public:
    bool isIsomorphic(string s, string t) {
        if(s.empty() && t.empty()) return true;
        if(s.length() != t.length()) return false;
        
        map<char, char> s_t_hsh; s_t_hsh.clear();
        map<char, char> t_s_hsh; t_s_hsh.clear();
        map<char, char>::iterator p_s_t, p_t_s;
        
        for(int i=0;i<s.length();++i) {
            p_s_t = s_t_hsh.find(s[i]); p_t_s = t_s_hsh.find(t[i]);
            if(p_s_t != s_t_hsh.end() && p_s_t->second != t[i]) return false;
            else s_t_hsh.insert(pair<char,char> (s[i],t[i]));
            
            if(p_t_s != t_s_hsh.end() && p_t_s->second != s[i]) return false;
            else t_s_hsh.insert(pair<char,char> (t[i],s[i]));
        }
        
        return true;
    }
};
leetcode 205: Isomorphic Strings

 

posted @ 2015-12-02 16:13  流白  阅读(204)  评论(0编辑  收藏  举报