leetcode筆記:Isomorphic Strings

來源:互聯網
上載者:User

標籤: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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.