Leetcode#87. Scramble String
Problem
We can scramble a string s to get a string t using the following algorithm:
- If the length of the string is 1, stop.
- If the length of the string is > 1, do the following:
- Split the string into two non-empty substrings at a random index, i.e., if the string is
s, divide it toxandywheres = x + y. - Randomly decide to swap the two substrings or to keep them in the same order. i.e., after this step,
smay becomes = x + yors = y + x. - Apply step 1 recursively on each of the two substrings
xandy.
- Split the string into two non-empty substrings at a random index, i.e., if the string is
Given two strings s1 and s2 of the same length, return true if s2 is a scrambled string of s1, otherwise, return false.
Example 1:
1 | Input: s1 = "great", s2 = "rgeat" |
Example 2:
1 | Input: s1 = "abcde", s2 = "caebd" |
Example 3:
1 | Input: s1 = "a", s2 = "a" |
Constraints:
s1.length == s2.length1 <= s1.length <= 30s1ands2consist of lowercase English letters.
Solve
題目簡單解釋,str分割可以得到 x1 + y1 ,可以互換,若能互換後相同就為scrambled
當初看超久
1 | rgeat |
前面gr 與 rg 為scrambled , eat當然就一樣
所以也能延伸
1 | greta |
at & ta ⇒ True ( scrambled ) → eat & ate ⇒ True
→ great & grate ⇒ True
1 | abb |
1 | bab |
這種情況也是 abb & bba ⇒True
由於 abb & bab ⇒ True 第一層互換
ab & ba ⇒ True → abb & bba ⇒ True
可以但超過時間
1 | # 類似用遞迴窮舉 |
借鏡別人的
做一個儲存庫
這樣不用每次都從新跑
1 | class Solution: |
1 | great & rgeta |
目前看到的最佳解之一
使用的Memory更少
1 | class Solution: |
本部落格所有文章除特別聲明外,均採用 CC BY-NC-SA 4.0 許可協議。轉載請註明來自 Imisky!
評論
