Class Solution

java.lang.Object
g0001_0100.s0087_scramble_string.Solution

public class Solution extends Object
87 - Scramble String.<p>Hard</p> <p>We can scramble a string s to get a string t using the following algorithm:</p> <ol> <li>If the length of the string is 1, stop.</li> <li>If the length of the string is > 1, do the following: <ul> <li>Split the string into two non-empty substrings at a random index, i.e., if the string is <code>s</code>, divide it to <code>x</code> and <code>y</code> where <code>s = x + y</code>.</li> <li><strong>Randomly</strong> decide to swap the two substrings or to keep them in the same order. i.e., after this step, <code>s</code> may become <code>s = x + y</code> or <code>s = y + x</code>.</li> <li>Apply step 1 recursively on each of the two substrings <code>x</code> and <code>y</code>.</li> </ul> </li> </ol> <p>Given two strings <code>s1</code> and <code>s2</code> of <strong>the same length</strong> , return <code>true</code> if <code>s2</code> is a scrambled string of <code>s1</code>, otherwise, return <code>false</code>.</p> <p><strong>Example 1:</strong></p> <p><strong>Input:</strong> s1 = &ldquo;great&rdquo;, s2 = &ldquo;rgeat&rdquo;</p> <p><strong>Output:</strong> true</p> <p><strong>Explanation:</strong> One possible scenario applied on s1 is: &ldquo;great&rdquo; &ndash;> &ldquo;gr/eat&rdquo; // divide at random index. &ldquo;gr/eat&rdquo; &ndash;> &ldquo;gr/eat&rdquo; // random decision is not to swap the two substrings and keep them in order. &ldquo;gr/eat&rdquo; &ndash;> &ldquo;g/r / e/at&rdquo; // apply the same algorithm recursively on both substrings. divide at ranom index each of them. &ldquo;g/r / e/at&rdquo; &ndash;> &ldquo;r/g / e/at&rdquo; // random decision was to swap the first substring and to keep the second substring in the same order. &ldquo;r/g / e/at&rdquo; &ndash;> &ldquo;r/g / e/ a/t&rdquo; // again apply the algorithm recursively, divide &ldquo;at&rdquo; to &ldquo;a/t&rdquo;. &ldquo;r/g / e/ a/t&rdquo; &ndash;> &ldquo;r/g / e/ a/t&rdquo; // random decision is to keep both substrings in the same order. The algorithm stops now and the result string is &ldquo;rgeat&rdquo; which is s2. As there is one possible scenario that led s1 to be scrambled to s2, we return true.</p> <p><strong>Example 2:</strong></p> <p><strong>Input:</strong> s1 = &ldquo;abcde&rdquo;, s2 = &ldquo;caebd&rdquo;</p> <p><strong>Output:</strong> false</p> <p><strong>Example 3:</strong></p> <p><strong>Input:</strong> s1 = &ldquo;a&rdquo;, s2 = &ldquo;a&rdquo;</p> <p><strong>Output:</strong> true</p> <p><strong>Constraints:</strong></p> <ul> <li><code>s1.length == s2.length</code></li> <li><code>1 <= s1.length <= 30</code></li> <li><code>s1</code> and <code>s2</code> consist of lower-case English letters.</li> </ul>
  • Constructor Details

    • Solution

      public Solution()
  • Method Details

    • isScramble

      public boolean isScramble(String s1, String s2)