205. Isomorphic Strings

原题链接:https://leetcode.com/problems/isomorphic-strings/description/
这是一道有意思的题目哦:

/**
 * Created by clearbug on 2018/2/26.
 */
public class Solution {

    public static void main(String[] args) {
        Solution s = new Solution();
        /**
         * For example,
         Given "egg", "add", return true.

         Given "foo", "bar", return false.

         Given "paper", "title", return true.
         */
        System.out.println(s.isIsomorphic("aa", "ab"));
        System.out.println(s.isIsomorphic("egg", "add"));
        System.out.println(s.isIsomorphic("foo", "bar"));
        System.out.println(s.isIsomorphic("paper", "title"));
    }

    /**
     * 讨论区某位大神的答案,确实简介无比啊!这道题目虽然不难,但是我并没有写出完整的实现。然后我又看了下 Related Topics,里面提到了
     * HashTable,现在才明白,这哥们的实现就是类似哈希表的思路啊,看来哈希表这种东西不单纯是一种数据结构,灵活运用可以解决很多问题啊!
     *
     * @param s
     * @param t
     * @return
     */
    public boolean isIsomorphic(String s, String t) {
        if (s == null || t == null || s.length() != t.length()) {
            return false;
        }

        int[] m1 = new int[256], m2 = new int[256];
        int n = s.length();
        for (int i = 0; i < n; i++) {
            if (m1[s.charAt(i)] != m2[t.charAt(i)]) {
                return false;
            }
            m1[s.charAt(i)] = i + 1;
            m2[t.charAt(i)] = i + 1;
        }

        return true;

    }

}
posted @ 2018-04-02 22:17  optor  阅读(96)  评论(0编辑  收藏  举报