leetcode--Scramble String

来源:互联网 发布:java如何防止sql注入 编辑:程序博客网 时间:2024/05/16 15:54

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.

题意:如图,判断两个字符串是否是scrambled关系。

分类:动态规划,字符串

解法1:三维动态规划。简单的说,就是s1和s2是scramble的话,那么必然存在一个在s1上的长度l1,将s1分成s11和s12两段,同样有s21和s22。
那么要么s11和s21是scramble的并且s12和s22是scramble的(条件1);
要么s11和s22是scramble的并且s12和s21是scramble的(条件2)。

思路是建立一个boolean flag[i][j][len],表明s1从i开始,s2从j开始,len长度的字符串,两者是不是scrambled关系。所以我们求的是flag[0][0][len]

根据上面的说法,要判断flag[i][j][len]是否为true,我们有两个判断依据

首先,我们尝试将s1分成两部分,因为起始序号是i,结束序号是i+len-1

假设我们从i开始,k长度把s1分成s11,s12,那么0<=k<=len

所以我们要判断res[i][j][k]&&res[i+k][j+k][len-k]是否为true,如果是,则满足条件1,

另外,我们还可以根据条件2

判断res[i][j+len-k][k]&&res[i+k][j][len-k]是否为true

public class Solution {    public boolean isScramble(String s1, String s2) {          if(s1==null || s2==null || s1.length()!=s2.length())              return false;          if(s1.length()==0)              return true;          boolean[][][] res = new boolean[s1.length()][s2.length()][s1.length()+1];          for(int i=0;i<s1.length();i++){              for(int j=0;j<s2.length();j++){                  res[i][j][1] = s1.charAt(i)==s2.charAt(j);              }          }          for(int len=2;len<=s1.length();len++){              for(int i=0;i<s1.length()-len+1;i++){                  for(int j=0;j<s2.length()-len+1;j++)  {                      for(int k=1;k<len;k++){                          res[i][j][len] |= res[i][j][k]&&res[i+k][j+k][len-k] || res[i][j+len-k][k]&&res[i+k][j][len-k];                      }                  }              }          }          return res[0][0][s1.length()];      }  }


0 0