题目:

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.

代码:

class Solution {
public:
bool isScramble(string s1, string s2) {
const int n1 = s1.size();
const int n2 = s2.size();
if (n1!=n2) { return false; }
const int n = n1;
int alpha[] = {};
for ( int i=; i<n; ++i ){ alpha[s1[i]-'a']++; alpha[s2[i]-'a']--; }
for ( int i=; i<; ++i ){ if ( alpha[i]!= ) return false; }
// terminal condition
if ( n== ) return s1[]==s2[];
// recursive process
for ( int i=; i<n; ++i ){
//cout << s1 << "," << s2 << ":" << i << endl;
if (
(
Solution::isScramble(s1.substr(,i), s2.substr(,i)) &&
Solution::isScramble(s1.substr(i,n-i), s2.substr(i,n-i))
)
||
(
Solution::isScramble(s1.substr(,i), s2.substr(n-i,i)) &&
Solution::isScramble(s1.substr(i,n-i), s2.substr(,n-i))
)
)
{ return true; }
}
return false;
}
};

tips:

这道题的题意自己并没有理解好,引用一个网上其他人的理解如下:

http://www.blogjava.net/sandy/archive/2013/05/22/399605.html

由于一个字符串有很多种二叉表示法,貌似很难判断两个字符串是否可以做这样的变换。
“对付复杂问题的方法是从简单的特例来思考,从而找出规律。
先考察简单情况:
字符串长度为1:很明显,两个字符串必须完全相同才可以。
字符串长度为2:当s1="ab", s2只有"ab"或者"ba"才可以。
对于任意长度的字符串,我们可以把字符串s1分为a1,b1两个部分,s2分为a2,b2两个部分,满足((a1~a2) && (b1~b2))或者 ((a1~b2) && (a1~b2))”

理解了题意,代码也就写出来了。

具体还有几个细节需要注意:

1. 为了剪枝并加快速度,做了如下几件事情:

  a) 判断s1与s2的长度是否相等

  b) 判断s1与s2的每个字符数量是否相等(这里由于是字母所以用一个定长数组alpha[26]表示:某个字母在s1中出现一次+1,在s2中出现一次-1;最终alpha的每个元素都是0则证明s1与s2的每个字符数量相等。扩展一下,如果字符不止26个字母,包含其他字符呢?可以用hashmap表示)

2. 设定终止条件:

  如果s1和s2长度已经为1,无法再分割了,就直接比较即可。

3. 在递归传入参数的时候,用到了substr(begin, num):

  a) begin代表切取的第一个字符下标,num代表截取几个字符

  b) 注意每次传入isScramble的字符长度相等

===========================================

上述的做法类似记忆化搜索,网上还有一种动态规划的解法,也学习了吧。

http://blog.csdn.net/linhuanmars/article/details/24506703

class Solution {
public:
bool isScramble(string s1, string s2) {
const int n1 = s1.size();
const int n2 = s2.size();
if ( n1 != n2 ) return false;
const int n = n1;
vector<vector<vector<bool> > > dp(n,vector<vector<bool> >(n,vector<bool>(n+,false)));
for ( int k=; k<=n; ++k )
{
for ( int i=; i<=n-k; ++i )
{
for ( int j=; j<=n-k; ++j )
{
if ( k== )
{
dp[i][j][k] = s1[i]==s2[j];
continue;
}
for ( int l=; l<k; ++l )
{
dp[i][j][k] =
(dp[i][j][l] && dp[i+l][j+l][k-l])
||
(dp[i][j+k-l][l] && dp[i+l][j][k-l]);
if ( dp[i][j][k] ) break;
}
}
}
}
/*
for ( int k=0; k<=n; ++k )
{
cout << k << endl;
for ( int i=0; i<n; ++i)
{
for (int j=0; j<n; ++j )
{
cout << dp[i][j][k] << " ";
}
cout << endl;
}
}
*/
return dp[][][n];
}
};

tips:

AC之后发现这道题的dp思路其实可以由递归思路得来。

递归算法在不断的递归过程中,其实是一直再算s1的某一段与s2等长的某一段是否符合scramble的特点;注意,这里的某一段不一定指的是s1和s2从同一个位置开始。递归过程中,并没有记录这样的s1、s2字串比较的历史信息;而dp的解法是比较一次记录一次比较的历史信息,下次再判断的时候就可以利用上历史的比较信息了。

dp的过程(http://blog.csdn.net/linhuanmars/article/details/24506703)已经说的很好了。

这里有个细节需要注意一下,就是最外层的循环k代表从s1和s2截取字符串的长度。这里为了在下标表示方便,定义为n+1维;这样的好处就在于循环中的k直接表示的就是需要比较的子字符串的长度,不用考虑k-1这一类的内容。

这题的dp思路太精妙,只能学习膜拜。

完毕。

===================================================

第二次过这道题,dp的做法没时间去过了,用“深搜+剪枝”的做法更直观一些。

class Solution {
public:
bool isScramble(string s1, string s2) {
if ( s1.size()!=s2.size() ) return false;
int count[] = {};
for ( int i=; i<s1.size(); ++i ){
count[(int)s1[i]]++;
count[(int)s2[i]]--;
}
for ( int i=; i<; ++i ) { if ( count[i]!= ) return false; }
if ( s1.size()== ) return s1[]==s2[];
for ( int l=; l<s1.size(); ++l ){
bool possible = Solution::isScramble(s1.substr(,l), s2.substr(,l)) &&
Solution::isScramble(s1.substr(l, s1.size()-l), s2.substr(l, s2.size()-l));
if ( possible ) return true;
possible = Solution::isScramble(s1.substr(,l), s2.substr(s2.size()-l,l)) &&
Solution::isScramble(s1.substr(l,s1.size()-l), s2.substr(,s2.size()-l));
if ( possible ) return true;
}
return false;
}
};

【Scramble String】cpp的更多相关文章

  1. 【Interleaving String】cpp

    题目: Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. For example,Given: ...

  2. 【Valid Sudoku】cpp

    题目: Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. The Sudoku board could ...

  3. 【WildCard Matching】cpp

    题目: Implement wildcard pattern matching with support for '?' and '*'. '?' Matches any single charact ...

  4. 【Add binary】cpp

    题目: Given two binary strings, return their sum (also a binary string). For example,a = "11" ...

  5. 【Implement strStr() 】cpp

    题目: Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if ne ...

  6. 【Valid Palindrome】cpp

    题目: Given a string, determine if it is a palindrome, considering only alphanumeric characters and ig ...

  7. 【Valid Parentheses】cpp

    题目: Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the ...

  8. 【Simplify Path】cpp

    题目: Given an absolute path for a file (Unix-style), simplify it. For example,path = "/home/&quo ...

  9. 【Valid Number】cpp

    题目: Validate if a given string is numeric. Some examples:"0" => true" 0.1 " = ...

随机推荐

  1. Java开发工具IntelliJ IDEA本地历史记录的使用方法

    IntelliJ IDEA的本地历史记录可以帮助用户记录并跟踪本地项目的更改,防止项目的意外丢失或来源于IDE之外的项目更改.本教程将展示如何使用本地历史记录查看和恢复某些项目更改. 1 .从头开始创 ...

  2. React 官网列子学习

    一个有状态的组件 除了接受输入数据(通过 this.props ),组件还可以保持内部状态数据(通过this.state ).当一个组件的状态数据的变化,展现的标记将被重新调用render() 更新. ...

  3. SQL Server DBA SQL

    . 监控事例的等待 ,,)) "Prev", ,,)) "Curr",count(*) "Tot" from v$session_Wait ...

  4. HDU1043 八数码(BFS + 打表)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1043 , 康托展开 + BFS + 打表. 经典八数码问题,传说此题不做人生不完整,关于八数码的八境界 ...

  5. 在linux 下为sublime Text 2 配置c#编译环境

    各位看官别笑我,在虚拟机上跑了了xp  xp里面安装了vs2008,然后电脑性能实在是太差了,所以装sublime用来编写代码,然后再统一由vs2008来调试. 说正事. 安装好sublime 之后, ...

  6. IOS 控件器的创建方式(ViewController)

    ● 控制器常见的创建方式有以下几种 ➢ 通过storyboard创建 ➢ 直接创建 NJViewController *nj = [[NJViewController alloc] init]; ➢ ...

  7. UVA 11990 ``Dynamic'' Inversion (序列分治)

    26天以前做过的一道题,之前的做法是分治预处理,树套树在线修改,复杂度为O(nlogn+m*logn*logn),代码量较大. 本来想学习一下cdq分治的,看到论文上的凸包.斜率就暂时放一边了,只知道 ...

  8. javascript中Array常用方法

    一.基本概念 1.什么是数组 数组就是一组数据的集合 其表现形式就是内存中的一段连续的内存地址 数组名称其实就是连续内存地址的首地址 2.关于js中的数组特点 数组定义时无需指定数据类型 数组定义时可 ...

  9. 动态规划专题(四)——单调队列优化DP

    前言 单调队列优化\(DP\)应该还算是比较简单容易理解的吧,像它的升级版斜率优化\(DP\)就显得复杂了许多. 基本式子 单调队列优化\(DP\)的一般式子其实也非常简单: \[f_i=max_{j ...

  10. python_35_进度条

    import sys for i in range(50): sys.stdout.write("+")#此命令不会像print语句执行一次,换行一次\ sys.stdout.fl ...