LeetCode| Scramble String
来源:互联网 发布:网络电视看电视台软件 编辑:程序博客网 时间:2024/06/11 02:06
题目:
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.
思路:
用递归可以非常简单地完成,但是递归时需要比较两种情况:
1)s1左侧与s2左侧比较,s1右侧与s2右侧比较
2)s1左侧与s2右侧比较,s1右侧与s2左侧比较
为了简化计算量,我们可以用动态规划的方法来完成。dp[l][i][j]中的l+1代表子字符串的长度,i代表s1的起始点,j代表s2的起始点。
代码:
class Solution {public: bool isScramble(string s1, string s2) { if(s1.size()!=s2.size()) { return false; } else { int len = s1.size(); bool*** dp = new bool**[len]; for(int i=0;i<len;i++) { dp[i]=new bool*[len]; for(int j=0;j<len;j++) { dp[i][j]=new bool[len]; } } for(int i=0;i<len;i++) { for(int j=0;j<len;j++) { dp[0][i][j]=(s1[i]==s2[j]); } } for(int l=2;l<=len;l++) { for(int i=0;i+l<=len;i++) { for(int j=0;j+l<=len;j++) { dp[l-1][i][j] = false; for(int k=1;k<=l-1;k++) { if(dp[k-1][i][j]&&dp[l-k-1][i+k][j+k]) { dp[l-1][i][j]=true; } else if(dp[k-1][i][j+l-k]&&dp[l-k-1][i+k][j]) { dp[l-1][i][j]=true; } } } } } return dp[len-1][0][0]; } }};
1 0
- LeetCode : Scramble String
- [LeetCode] Scramble String
- [LeetCode] Scramble String
- [Leetcode] Scramble String
- [leetcode] Scramble String
- LeetCode: Scramble String
- [LeetCode]Scramble String
- [leetcode]Scramble String
- Leetcode:Scramble String
- LeetCode-Scramble String
- LeetCode Scramble String
- [leetcode] Scramble String
- [LeetCode] Scramble String
- LeetCode - Scramble String
- [LeetCode]Scramble String
- [LeetCode] Scramble String
- Leetcode: Scramble String
- leetcode Scramble String
- 【设计模式基础】创建型模式 - 2 - 抽象工厂(Abstract Factory)
- Exports and Metadata
- 基于堆栈的计算器实现算法
- CSDN排名变化 2013-10到2013-12
- javascript中的强制类型转换
- LeetCode| Scramble String
- 初识Python -- 关于类型的困惑
- hadoop深入研究:(九)——mapreduce中的压缩
- ARM+Linux嵌入式底层内核驱动方向学习总体路线图(转)
- Catalogs
- 备份Ubuntu的工具—Remastersys
- java 将TXT中数据插入数据库
- svn 创建分支简单方法
- BT656/BT601/BT1120协议以及DM365/DM355/DM6467上使用的YUV颜色空间说明