LeetCode 题解(197) : 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.

题解:

HashTable + used数组。

C++版:

class Solution {
public:
    bool isIsomorphic(string s, string t) {
        unordered_map<char, char> n;
        vector<bool> used(95, false);
        for(int i = 0; i < s.length(); i++) {
            if(n.find(s[i]) != n.end()) {
                if(n[s[i]] != t[i])
                    return false;
                continue;
            }
            if(used[t[i] - ' '])
                return false;
            n.insert(pair<char, char>(s[i], t[i]));
            used[t[i] - ' '] = true;
        }
        return true;
    }
};

Java版:

import java.util.Hashtable;

public class Solution {
    public boolean isIsomorphic(String s, String t) {
        Hashtable<Character, Character> m = new Hashtable<>();
        boolean[] used = new boolean[95];
        for(int i = 0; i < s.length(); i++) {
            if(m.containsKey(s.charAt(i))) {
                if(m.get(s.charAt(i)) != t.charAt(i))
                    return false;
                continue;
            }
            if(used[t.charAt(i) - ' '])
                return false;
            m.put(s.charAt(i), t.charAt(i));
            used[t.charAt(i) - ' '] = true;
        }
        return true;
    }
}

Python版:

class Solution(object):
    def isIsomorphic(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        d = {}
        used = [False] * 95
        for i in range(len(s)):
            if s[i] in d:
                if d[s[i]] != t[i]:
                    return False
                continue
            if used[ord(t[i]) - ord(" ")]:
                return False
            d[s[i]] = t[i]
            used[ord(t[i]) - ord(" ")] = True
        return True

你可能感兴趣的:(Algorithm,LeetCode,面试题)