1. 程式人生 > >Leetcode:205. Isomorphic Strings (同構字串)

Leetcode:205. 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.

先說一下:
據一對一對映的特點,我們需要用兩個雜湊表分別來記錄原字串和目標字串中字元出現情況,由於ASCII碼只有128個字元,所以我們可以用一個128大小的陣列來代替雜湊表,並初始化為0,我們遍歷原字串,分別從源字串和目標字串取出一個字元,然後分別在兩個雜湊表中查詢其值,若不相等,則返回false,若相等,將其值更新為i + 1

程式碼如下;

int m1[] = new int[128], m2[] = new int[128], n = s.length();
        for (int i = 0; i < n; ++i) {
            //比如aba
            //比如cfc
            //i=0    m1[97]=0   m2[99]=0
            //i=1    m1[98]=0   m2[102]=0
            //Now WILL APPERAR the number had apperaed。
            //i=2    m1[97]=1   m2[99]=1 ------> 從這裡看出同構 如果不同構的話,那麼m2[]此刻的值肯定不等於1
if (m1[s.charAt(i)] != m2[t.charAt(i)]) return false; //下面的作用相當於鍵 起標識作用 //現在s.charAt(i)對應的ASCII碼對應的位置等於i+1; //m1[97] = 1 //m1[98]= 2 m1[s.charAt(i)] = i + 1; //現在t.charAt(i)對應的ASCII碼對應的位置等於i+1; //m2[99] = 1; //m2[102] = 2; m2[t.charAt(i)] = i + 1; } return true;