標籤:leetcode c++ string vector ascii
一.題目描述
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編碼的字元只有256個,而且string中是不儲存null字元的,因此,可以建立兩個大小為256的字元數組來儲存兩個string中每一個字元在另外一個string中的對應的關係,然後遍曆string中的每一個字元,如果相同位置的字元是互相對應的話,就處理下一個字元,如果不是互相對應的話,就在說明這兩個string不是同等結構的。
也可以通過兩個map來實現,但是map的尋找過程時間複雜度為O(lgn),但是上面對於string中的每一個字串都需要尋找,因此,使用map的話,時間複雜度太高了。也可以使用hash表來做,也就是使用unordered_map來實現,但是由於ASCII編碼的字元的個數是固定的而且個數比較少,使用數組完全可以很好地實現。
三.範例程式碼
#include <string> #include <vector> using std::string; using std::vector; class Solution { public: bool isIsomorphic(string s, string t) { vector<unsigned char> First(256, 0); // 建立一個含有256個0拷貝的vector vector<unsigned char> Second(256, 0); const int SIZE = s.size(); for (int Index = 0; Index < SIZE; Index++) { unsigned char ElementOfFirst = s[Index]; unsigned char ElementOfSecond = t[Index]; unsigned char& First2Second = First[ElementOfSecond]; unsigned char& Second2First = Second[ElementOfFirst]; if (First2Second != 0 && Second2First != 0) { if (First2Second != ElementOfFirst) { return false; } if (Second2First != ElementOfSecond) { return false; } continue; } if (First2Second == 0 && Second2First == 0) { First2Second = ElementOfFirst; Second2First = ElementOfSecond; continue; } return false; } return true; } };
四.小結
這道題就是尋找一個好的資料結構來儲存兩個string之間的字元的對應關係,根據這道題的假設,選擇數組是一個比較的解決方案。
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
leetcode筆記:Isomorphic Strings