Tuesday, August 18, 2015

Leetcode:Isomorphic Strings(hash table) solution

Isomorphic Strings

 Total Accepted: 24117 Total Submissions: 97680My Submissions
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.
Hide Tags
 Hash Table



























---------------------------------------------------

Using two map to maintain the mapping information, where the mapping is identified by the same second value, e.g.:

unordered_map<char, int> tmp1, tmp2;
tmp1[s[i]] = i;
tmp2[t[i]] = i;



///////////////////////////////////////////////////////////////////////
// code
class Solution {
class Solution {
public:
       bool isIsomorphic(string s, string t) {
              unordered_map<char, int> tmp1, tmp2;
              for (int i = 0; i<s.size(); i++){
                     //check the current item in the pool
                     //if not exist
                     if (tmp1.find(s[i]) == tmp1.end() && tmp2.find(t[i]) != tmp2.end())return false;
                     if (tmp1.find(s[i]) != tmp1.end() && tmp2.find(t[i]) == tmp2.end())return false;
                     //if exist
                     if (tmp1.find(s[i]) != tmp1.end() && (tmp1[s[i]]) != (tmp2[t[i]]))return false;

                     //fill the map
                     tmp1[s[i]] = i;
                     tmp2[t[i]] = i;
                     //check duplication
                     if (tmp1.size() != tmp2.size())return false;
              }
              return true;
       }

};

No comments:

Post a Comment