leetcode - interleaving string

來源:互聯網
上載者:User

標籤:interleaving string   leetcode   

題目描述:

Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.

For example,
Given:
s1 = "aabcc",
s2 = "dbbca",

When s3 = "aadbbcbcac", return true.
When s3 = "aadbbbaccc", return false.

最直觀的做法,定義一個三維的狀態數組 f[ k ] [ i ] [ j ] 表示s3[0 ... k-1] 是 s1[0 ... i ] 和 s2[0 ... j ]交錯而成。

那麼狀態式定義為:

f[ k ] [ i ] [ j ]     =    ( f [ k-1 ] [i ] [ j - 1]  && s2[ j-1] == s3  [ k -1]  // s2的第j-1個字元與s3的第k-1個字元匹配。

或者是            =    ( f [ k-1 ] [ i-1 ] [ j ]  && s1 [ i-1] == s3  [ k -1]  // s1的第i-1個字元與s3的第k-1個字元匹配。

兩者只要有一個滿足條件即可。

代碼如下:

Version 1:  時間複雜度 O(n^3),空間複雜度 O(n^3).Time : ~200ms


Version 2:  時間複雜度 O(n^2),空間複雜度 O(n^2).Time :~ 4ms


Version 3:  時間複雜度 O(n^2),空間複雜度 O(n). Time :~ 4ms

使用滾動數組來解決:




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.