# leetcode解題:(Easy) 205. Isomorphic Strings 題目:[https://leetcode.com/problems/isomorphic-strings/](https://leetcode.com/problems/isomorphic-strings/) 描述:判斷2個字串是否同構(isomorphic)。如果將一個字串中每個特定字元轉換成另一個特定字元後能夠與另一個字串相同,則這2個字串即為同構 解題思路:因為同構每個特定字元只能對應另一個特定字元且不能重複對應,所以只要用map將第一次出現的對應記錄下來,判斷有出現的字元在另一個字串是否有正確對應即可 程式碼: ```JAVA= class Solution { public boolean isIsomorphic(String s, String t) { HashMap<Character, Character> map = new HashMap<Character, Character>(); for(int i = 0; i < s.length(); i++) { //在s中第一次出現的字元 if(!map.containsKey(s.charAt(i))) { //t也沒有對應過這個字元->第一次出現的對應,新增到map中 if(!map.containsValue(t.charAt(i))) map.put(s.charAt(i), t.charAt(i)); //t中有字元已經有對應過這個字元->s跟t不同構 else return false; } //已經紀錄過的對應,但t中的字元不相符->s跟t不同構 else if(map.get(s.charAt(i)) != t.charAt(i)) return false; } //確認過s跟t所有字元對應都相符->s跟t同構 return true; } } ``` 時間複雜度:O(n) 空間複雜度:O(n) ###### tags: `leetcode` `easy` `map/set`