码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】Scramble String

时间:2015-01-19 23:28:51      阅读:244      评论:0      收藏:0      [点我收藏+]

标签:

Scramble String

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. 如果两个substring相等的话,则为true
2. 如果两个substring中间某一个点,左边的substrings为scramble string, 同时右边的substrings也为scramble string,则为true
3. 如果两个substring中间某一个点,s1左边的substring和s2右边的substring为scramble string, 同时s1右边substring和s2左边的substring也为scramble string,则为true
 
 
 1 class Solution {
 2 public:
 3     bool isScramble(string s1, string s2) {
 4        
 5         int n=s1.length();
 6         vector<vector<vector<bool>>> dp(n,vector<vector<bool>>(n,vector<bool>(n+1)));
 7         //dp[i][j][k] represent whether s1[i,i+1,...,i+k-1] and  s2[j,j+1,...,j+k-1] is scramble
 8        
 9        
10         for(int i=n-1;i>=0;i--)
11         {
12             for(int j=n-1;j>=0;j--)
13             {
14                 for(int k=1;k<=n-max(i,j);k++)
15                 {
16                     if(s1.substr(i,k)==s2.substr(j,k))
17                     {
18                         dp[i][j][k]=true;
19                     }
20                     else
21                     {
22                         for(int l=1;l<k;l++)
23                         {
24                             if(dp[i][j][l]&&dp[i+l][j+l][k-l]||dp[i][j+k-l][l]&&dp[i+l][j][k-l])
25                             {
26                                 dp[i][j][k]=true;
27                                 break;
28                             }
29                         }
30                
31                     }
32                 }
33             }
34  
35         }
36         return dp[0][0][n];
37     }
38 };

 

【leetcode】Scramble String

标签:

原文地址:http://www.cnblogs.com/reachteam/p/4234925.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!