Scramble String
2015-06-16 23:14
211 查看
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 =
To scramble the string, we may choose any non-leaf node and swap its two children.
For example, if we choose the node
string
We say that
Similarly, if we continue to swap the children of nodes
it produces a scrambled string
We say that
Given two strings s1 and s2 of the same length, determine if s2 is a scrambled string of s1.
解题思路:简单的四维DP。
dp[i1][j1][i2][j2]表示s1的i1->j1的子串和s2的i2->j2的子串是否匹配。
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.
解题思路:简单的四维DP。
dp[i1][j1][i2][j2]表示s1的i1->j1的子串和s2的i2->j2的子串是否匹配。
class Solution { public: bool isScramble(string s1, string s2) { int n = s1.length(); bool dp[30][30][30][30]; memset(dp, false, sizeof(dp)); for(int i = 0; i < n; ++i) { for(int j = 0; j < n; ++j) { if(s1[i] == s2[j]) { dp[i][i][j][j] = true; } } } for(int k = 1; k < n; ++k) { for(int i1 = 0; i1 + k < n; ++i1) { for(int i2 = 0; i2 + k < n; ++i2) { int j1 = i1 + k; int j2 = i2 + k; for(int l = i1; l < j1; ++l) { dp[i1][j1][i2][j2] |= (dp[i1][l][i2][i2+l-i1]&dp[l+1][j1][i2+l-i1+1][j2]); dp[i1][j1][i2][j2] |= (dp[i1][l][j2-(l-i1)][j2]&dp[l+1][j1][i2][i2+j1-l-1]); } } } } return dp[0][n-1][0][n-1]; } };
相关文章推荐
- 线程
- 使用CodeMirror在浏览器中实现编辑器的代码高亮效果
- HTML formatting
- 探索Eclipse的OSGi控制台
- 离职申请书
- Golang学习书籍和论坛推荐
- linux磁盘的基本概念
- Java基础(一)
- k-近邻算法
- 转载--thinkphp框架的路径问题 - 总结
- Theano2.1.10-基础知识之循环
- Python产生随机数
- 一、Linux USB驱动之USB规范初探
- Animation Frame动画实现应用的欢迎界面
- Leetcode 75 Sort Colors
- Theano2.1.10-基础知识之循环
- python中if __name__ == '__main__': 的解析
- 黑马程序员—————JAVA语言j基础Date日期类和Calendar日类类详解。
- Filter Chain in J2EE : revise response header
- LeetCode —— Merge k Sorted Lists