[LeetCode] Scramble String

来源:互联网 发布:网络语言翔是什么意思 编辑:程序博客网 时间:2024/06/10 12:37

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.

在此介绍两种方法

方法一:dfs暴力搜索

方法二:三维动态规划(学习别人的方法)

方法一:

public class Solution2 {  public boolean isScramble(String s1, String s2) {  if(s1.equals(s2)) return true;  int map[]=new int[26];//没有这一步会超时      for(int i=0;i<s1.length();i++) map[s1.charAt(i)-'a']++;      for(int i=0;i<s2.length();i++){      if(--map[s2.charAt(i)-'a']<0)      return false;      }      for(int i=0;i<s1.length()-1;i++){      String s11=s1.substring(0,i+1);      String s12=s1.substring(i+1,s1.length());      String s21=s2.substring(0,i+1);      String s22=s2.substring(i+1,s2.length());      if(isScramble(s11, s21)&&isScramble(s12, s22)) return true;      String s23=s2.substring(0,s1.length()-i-1);      String s24=s2.substring(s1.length()-i-1,s1.length());      if(isScramble(s11, s24)&&isScramble(s12, s23)) return true;      }      return false;  }  public static void main(String[] args) {Solution2 s=new Solution2();System.out.println(s.isScramble("a", "a"));}}
方法二:

public class Solution3 { public boolean isScramble(String s1, String s2) { if(s1.length()!=s2.length()) return false; int len=s1.length(); boolean[][][] dp=new boolean[len][len][len+1]; for(int i=0;i<len;i++){ for(int j=0;j<len;j++){ if(s1.charAt(i)==s2.charAt(j))dp[i][j][1]=true; } } for(int k=2;k<=len;k++){ for(int i=0;i<=len-k;i++){ for(int j=0;j<=len-k;j++){for(int l=1;l<k;l++){dp[i][j][k]=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]);} } } } return dp[0][0][len]; } public static void main(String[] args) {Solution3 s=new Solution3();System.out.println(s.isScramble("abb", "bba"));}}


原创粉丝点击