Thursday, April 30, 2015

LeetCode [205] Isomorphic Strings

 205. Isomorphic Strings

Easy

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: true

Example 2:

Input: s = "foo", t = "bar"
Output: false

Example 3:

Input: s = "paper", t = "title"
Output: true

Note:
You may assume both and have the same length.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
public:
    bool isIsomorphic(string s, string t) {
        int ns = s.size(), nt = t.size();
        if(ns!=nt) return false;
        unordered_map<char, char> hash1, hash2;
        
        for(int i=0; i<ns; ++i){
            if(hash1.count(s[i])>0 && hash1[s[i]]!=t[i]) return false;
            hash1[s[i]] = t[i];
            
            if(hash2.count(t[i])>0 && hash2[t[i]]!=s[i]) return false;
            hash2[t[i]] = s[i];           
        }
        return true;
    }
};

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
    Map<Character, Character> map1 = new HashMap<>();
    Map<Character, Character> map2 = new HashMap<>();
    public boolean isIsomorphic(String s, String t) {
        for(int i=0; i<s.length(); ++i){
            char c1 = s.charAt(i), c2 = t.charAt(i);
            if(!map1.containsKey(c1)) map1.put(c1, c2);
            if(!map2.containsKey(c2)) map2.put(c2, c1);
            
            if(map1.get(c1)!=c2 || map2.get(c2)!=c1) return false;
        }
        return true;
    }
}

No comments:

Post a Comment