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.

思考:怎麼才能一一映射

想法:

  • 1、用兩個char數組存放每一位的char(ASCII碼),並且將相對應位上得char值映射到同一數值
  • 2、如果以相應的ascii碼爲索引得到的數字不同,則證明不同構。

代碼

public class Solution {
    public boolean isIsomorphic(String s, String t) {
        int[] tranS = new int[256];
        int[] tranT = new int[256];
        for(int i = 0; i < s.length(); i++){
            int sIndex = (int)s.charAt(i);
            int tIndex = (int)t.charAt(i);
            //沒有賦值之前都爲0
            if(tranS[sIndex] != tranT[tIndex])
                return false;
            //賦值之後每一元素都不爲0,只有沒有遍歷的元素才爲0,將賦值之後的元素與賦值之前區分
            tranS[sIndex] = i + 1;
            tranT[tIndex] = i + 1;  
        }
        return true;   
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章