87. Scramble String
来源:互联网 发布:数据泄露防护系统 编辑:程序博客网 时间:2024/06/06 21:04
字符串分解成两颗子树,子树的长度任意,所有可以用递归
class Solution {public: bool isScramble(string s1, string s2) { int n=s1.size(); int m=s2.size(); int i; if(n!=m) return false; int alp1[26],alp2[26]; memset(alp1,0,sizeof(alp1)); memset(alp2,0,sizeof(alp2)); bool same=true; for(i=0;i<n;i++) { if(s1[i]!=s2[i]) same=false; alp1[s1[i]-'a']++; alp2[s2[i]-'a']++; } if(same) return true; for(i=0;i<26;i++) { if(alp1[i]!=alp2[i]) return false; } for(i=1;i<=n-1;i++) { if(isScramble(s1.substr(0,i),s2.substr(0,i))&&isScramble(s1.substr(i),s2.substr(i))||isScramble(s1.substr(0,i),s2.substr(n-i))&&isScramble(s1.substr(i),s2.substr(0,n-i))) return true; } return false; }};
方法2:
可以使用动态规划,
class Solution {public: bool isScramble(string s1, string s2) { int n=s1.size(); int m=s2.size(); if(n!=m) return false; if(s1==s2) return true; bool dp[n][n][n]; memset(dp,false,sizeof(dp));//s1从i开始,s2从j开始,长度为len 的字符串是否时scramble int i,j,k; for(i=0;i<n;i++) { for(j=0;j<n;j++) dp[i][j][1]=(s1[i]==s2[j]); } for(int len=2;len<=n;len++) { for(i=0;i<=n-len;i++) for(j=0;j<=n-len;j++) { for(k=1;k<len&&!dp[i][j][len];k++) { dp[i][j][len]=dp[i][j][len]||dp[i][j][k]&&dp[i+k][j+k][len-k]|| dp[i+len-k][j][k]&&dp[i][j+k][len-k]||dp[i][j+len-k][k]&&dp[i+k][j][len-k]; } } } return dp[0][0][n]; }};
0 0
- LeetCode 87. Scramble String
- [Leetcode] 87. Scramble String
- LeetCode --- 87. Scramble String
- 87. Scramble String
- [leetcode] 87.Scramble String
- 87. Scramble String
- LeedCode 87. Scramble String
- 87. Scramble String
- Leetcode 87. Scramble String
- Leetcode 87. Scramble String
- Leetcode:87. Scramble String
- leetcode.87. Scramble String
- 87. Scramble String
- Leetcode 87. Scramble String
- 87. Scramble String
- 87. Scramble String
- [LeetCode] 87. Scramble String
- 87. Scramble String
- IOS中延时执行的几种方式的比较和汇总
- 我做草根站长的这两年,靠互联网赚钱到底难不难
- 程序员进阶的10大黄金法则
- bzoj 1832: [AHOI2008]聚会 lca
- EXTJS4.0 3种和后台交互数据的方法
- 87. Scramble String
- LeetCode: Two Sum II - Input array is sorted
- 文字记忆
- NYOJ17-LIS优化
- 继承
- 全角转半角笔记
- 在PHP中使用Mysqli操作数据库
- JAVA 网络编程 Socket 详细说明,实现客户端和服务端相互推送消息
- MyBatis学习总结(八)——Mybatis3.x与Spring4.x整合