###### tags: `Leetcode` `easy` `string` `python` `c++` # 205. Isomorphic Strings ## [題目連結:] https://leetcode.com/problems/isomorphic-strings/ ## 題目: Given two strings s and t, determine if they are isomorphic. Two strings s and t 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. **Example 1:** ``` Input: s = "egg", t = "add" Output: true ``` **Example 2:** ``` Input: s = "foo", t = "bar" Output: false ``` **Example 3:** ``` Input: s = "paper", t = "title" Output: true ``` ## 解題想法: 兩組字串分別紀錄每個單字出現的位置為編號,進行比對 ## Python: ``` python= class Solution(object): def isIsomorphic(self, s, t): sList=[] tList=[] for i in s: #string.find('str') find str's index in string sList.append(s.find(i)) for i in t: tList.append(t.find(i)) return sList==tList if __name__ == '__main__': result = Solution() s = "egg" t = "add" ans = result.isIsomorphic(s,t) print(ans) ``` ## C++: ``` cpp= #include<iostream> #include<vector> using namespace std; class Solution { public: bool isIsomorphic(string s, string t) { vector<int> s_list; vector<int> t_list; for (char val: s){ s_list.push_back(s.find(val)); } for (char val: t){ t_list.push_back(t.find(val)); } return s_list==t_list; } }; int main(){ string s="egg"; string t="add"; Solution res; bool ans=res.isIsomorphic(s,t); cout<<ans<<endl; return 0; } ```