LeetCode 87 Scramble String (Python详解及实现)
来源:互联网 发布:ubuntu 3306 开放 编辑:程序博客网 时间:2024/04/29 08:49
【题目】
Given a string s1, we may represent it as abinary 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 anynon-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 ascrambled string of "great".
Similarly, if we continue to swap thechildren of nodes "eat" and "at", it produces a scrambledstring "rgtae".
rgtae
/ \
rg tae
/\ / \
r g ta e
/ \
t a
We say that "rgtae" is ascrambled string of "great".
Given two strings s1 and s2 of the samelength, determine if s2 is a scrambled string of s1.
首先解释一下scramble:给定一个字符串,字符串展成一个二叉树,如果二叉树某个或多个左右子树颠倒得到新的字符串,这就是所谓得scramble。本题要做的是给定两个字符串,判断是否互为scramble。
【思路】
可以使用递归。
【Python实现】
class Solution(object): def isScramble(self, s1, s2): """ :type s1: str :type s2: str :rtype: bool """ if len(s1) != len(s2): return False if s1 == s2: return True if sorted(s1) != sorted(s2): return False sl_len = len(s1) f = self.isScramble for i in range(1, sl_len): if f(s1[i:], s2[i:]) and f(s1[:i], s2[:i]): return True if f(s1[i:], s2[:sl_len - i]) and f(s1[:i], s2[sl_len - i:]): return True return False
- LeetCode 87 Scramble String (Python详解及实现)
- LeetCode: Scramble String [87]
- LeetCode 87 Scramble String
- [leetcode 87] Scramble String
- leetcode 87: Scramble String
- leetcode 87: Scramble String
- leetcode 87:Scramble String
- LeetCode #87: Scramble String
- Leetcode 87 Scramble String
- LeetCode 87 Scramble String
- 87. Scramble String Leetcode Python
- [leetcode]87. Scramble String @python
- Leetcode NO.87 Scramble String
- [leetcode-87]Scramble String(java)
- LeetCode(87) Scramble String
- 【LeetCode】87. Scramble String解法及注释
- LeetCode 97 Interleaving String(Python详解及实现)
- leetcode 87 Scramble String(递归+剪枝)
- JAVA23中
- JVM优化2-TProfiler
- TCP恋爱与分手过程
- hadoop集群balance工具详解
- 正则表达式中数量词的贪婪和非贪婪
- LeetCode 87 Scramble String (Python详解及实现)
- vtk 使用renderwindowControl 时提示“未能加载文件或程序集” 解决方法
- Ray Allen (篮球的爱)
- TI ZigBee协议栈中终端设备的状态切换详解
- Jmeter使用代理录制脚本
- QQ通信原理及QQ是怎么穿透内网进行通信的?
- Trafodion集成Apache Zeppelin实现报表可视化
- fragment中使用百度地图的两个坑
- .Net 4.0 之 Dynamic 动态类型