87. Scramble String Leetcode Python

Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively.

Below is one possible representation of s1 = "great":

    great
   /    \
  gr    eat
 / \    /  \
g   r  e   at
           / \
          a   t

To scramble the string, we may choose any non-leaf node and swap its two children.

For example, if we choose the node "gr" and swap its two children, it produces a scrambled string "rgeat".

    rgeat
   /    \
  rg    eat
 / \    /  \
r   g  e   at
           / \
          a   t

We say that "rgeat" is a scrambled string of "great".

Similarly, if we continue to swap the children of nodes "eat" and "at", it produces a scrambled string "rgtae".

    rgtae
   /    \
  rg    tae
 / \    /  \
r   g  ta  e
       / \
      t   a

We say that "rgtae" is a scrambled string of "great".

Given two strings s1 and s2 of the same length, determine if s2 is a scrambled string of s1.



This problem can be solved with brute Force.

class Solution:
    # @param s1, a string
    # @param s2, a string
    # @return a boolean
    def isScramble(self, s1, s2):
        n, m = len(s1),len(s2)
        if n!=m or sorted(s1)!=sorted(s2):
            return False
        if n < 4 or s1 == s2:
            return True
        for i in range(1, n):
            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[:-i]) ):
                return True
        return False
        
            



参考资源链接:[C语言实现LeetCode87题字符串错乱问题详解](https://wenku.csdn.net/doc/3gininbodv?utm_source=wenku_answer2doc_content) 对于想要精通C语言并解决复杂字符串算法问题的程序员来说,解决LeetCode上的Scramble String问题是一个不错的实践。这不仅能够锻炼对字符串操作的熟练度,还能加强递归和动态规划的理解。 解决Scramble String问题的核心在于判断两个字符串是否由相同的字符以不同顺序组成。在C语言中,我们可以通过递归函数来实现这一判断。具体步骤如下: 1. 首先,如果两个字符串长度不同,则直接返回false。 2. 检查两个字符串是否完全相同,如果完全相同,则返回true。 3. 对于字符串s1中的每一个字符,尝试所有的划分点,即在s1中找到一个分割线,将s1划分为s1a和s1b两部分。 4. 对于每一个划分点,检查s1a是否能够错乱成s2的某个前缀,并且s1b是否能错乱成s2的相应后缀,或者s1a是否能够错乱成s2的某个后缀,s1b是否能错乱成s2的相应前缀。 5. 如果任何一个划分点满足条件,则返回true。 6. 如果所有划分点都不满足条件,则返回false。 7. 为了避免重复计算,我们可以使用一个二维数组dp来记录已经计算过的情况,这样可以减少不必要的递归调用,提高程序效率。 下面是C语言的源代码示例,展示了如何实现上述步骤: (源代码示例代码,此处略) 通过上述步骤和代码示例,你可以用C语言解决LeetCode上的Scramble String问题。如果你希望获得更加详细和深入的理解,我强烈建议查阅这份资料:《C语言实现LeetCode87题字符串错乱问题详解》。这份资源不仅提供了实战案例,还包含了针对该问题的详细讲解和源代码,是学习C语言和算法编程的宝贵资料。 参考资源链接:[C语言实现LeetCode87题字符串错乱问题详解](https://wenku.csdn.net/doc/3gininbodv?utm_source=wenku_answer2doc_content)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值