Tuesday, April 28, 2015

[LeetCode] Isomorphic Strings

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.
Note:
You may assume both s and t have the same length.
Solution: Hash table. The test cases assume ASCII characters. A valid mapping is indeed a bijection. The easiest way to determine whether such a mapping exists is to test both directions. The beauty of symmetry!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class Solution {
    public boolean isIsomorphicOneWay(String s, String t) {
        char[] map = new char[256];
        Arrays.fill(map, '*');
        for (int i = 0; i < s.length(); i++) {
            int idx = (int)s.charAt(i);
            if (map[idx] == '*') {
                map[idx] = t.charAt(i);
            } else {
                if (map[idx] != t.charAt(i)) {
                    return false;
                }
            }
        }
        return true;
    }
    
    public boolean isIsomorphic(String s, String t) {
        if (s.length() != t.length()) {
            return false;
        }
        return isIsomorphicOneWay(s, t) &&
               isIsomorphicOneWay(t, s);
    }
}

No comments:

Post a Comment