判断是否字符串重组 Scramble String @LeetCode

2014-11-24 07:25:37 · 作者: · 浏览: 0

思路:

1 递归:

简单的说,就是s1和s2是scramble的话,那么必然存在一个在s1上的长度l1,将s1分成s11和s12两段,同样有s21和s22。
那么要么s11和s21是scramble的并且s12和s22是scramble的;
要么s11和s22是scramble的并且s12和s21是scramble的。

如果要能通过OJ,还必须把字符串排序后进行剪枝

http://blog.unieagle.net/2012/10/23/leetcode%E9%A2%98%E7%9B%AE%EF%BC%9Ascramble-string%EF%BC%8C%E4%B8%89%E7%BB%B4%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92/


2 DP:

使用了一个三维数组boolean result[len][len][len],其中第一维为子串的长度,第二维为s1的起始索引,第三维为s2的起始索引。
result[k][i][j]表示s1[i...i+k]是否可以由s2[j...j+k]变化得来。

http://www.blogjava.net/sandy/archive/2013/05/22/399605.html


package Level5;

import java.util.Arrays;


/**
 * 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.
 *
 */
public class S87 {

	public static void main(String[] args) {
		String s1 = "abab";
		String s2 = "bbaa";
		
		System.out.println(isScramble(s1, s2));
		System.out.println(isScrambleDP(s1, s2));
	}
	
	public static boolean isScramble(String s1, String s2) {
		if(s1.length() != s2.length()){
			return false;
		}
        if(s1.length()==1 && s2.length()==1){
        	return s1.charAt(0) == s2.charAt(0);
        }
        
        // 排序后可以通过
        char[] s1ch = s1.toCharArray();
		char[] s2ch = s2.toCharArray();
		Arrays.sort(s1ch);
		Arrays.sort(s2ch);
		if(!new String(s1ch).equals(new String(s2ch))){
			return false;
		}
		
		for(int i=1; i
  
   =0; i--){			// s1[i...i+k]
				for(int j=len-k; j>=0; j--){	// s2[j...j+k]
					boolean canTransform = false;
					for(int m=1; m