LeetCode Scramble String
Scramble String for solving LeetCode Problems
Original question
A string can be split into two substrings that are not empty, and the substring (length greater than or equal to two) can be further split, now we can change the character order of the string by exchanging the positions of the two parts. Determine whether two characters can be converted to each other in this way.
Note: This question is difficult to describe in language. For more information, see the legend in the original question.
Click here for the original question
Note:
The two strings are equal in length.
Example:
Input: s1 = "rgtae", s2 = "great"
Output: True ("rgtae"-> "grtae"-> "greta"-> "great ")
Solutions
I am not very familiar with 3D dynamic planning. I am lazy and use the simplest recursive method. I will introduce the dynamic planning solution later. To determine whether two characters S and T can be converted, we must first divide them into two parts. If the First Half of S and the first half of T can be converted, the second half can also be converted, it means they can be converted, but it is also possible that the first half and the second half of S are converted back in the last exchange, that is, the first half of S and the second half of T can be converted, while the first half of T can be converted to the second half. We can also make some optimizations based on my code. For example, we can determine in advance whether the numbers of Characters in the two strings to be converted are equal for pruning to reduce unused recursion. The pruning recursive algorithm is still very fast.
AC Source Code
from collections import defaultdictclass Solution(object): def isScramble(self, s1, s2): """ :type s1: str :type s2: str :rtype: bool """ if s1 == s2: return True count1 = defaultdict(int) count2 = defaultdict(int) for e1, e2 in zip(s1, s2): count1[e1] += 1 count2[e2] += 1 if count1 != count2: return False for i in range(1, len(s1)): if self.isScramble(s1[:i], s2[:i]) and self.isScramble(s1[i:], s2[i:]) \ or self.isScramble(s1[:i], s2[-i:]) and self.isScramble(s1[i:], s2[:len(s2) - i]): return True return False