leetcode -- 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.
[解题思路]
DFS+Pruning
DFS的终止条件,以及使用pruning来减少不必要的比较
1 public boolean isScramble(String s1, String s2) { 2 // Start typing your Java solution below 3 // DO NOT write main() function 4 int len1 = s1.length(), len2 = s2.length(); 5 if(len1 != len2){ 6 return false; 7 } 8 9 int[] count = new int[26]; 10 for(int i = 0; i < len1; i++){ 11 count[s1.charAt(i) - 'a'] ++; 12 } 13 14 for(int i = 0; i < len2; i++){ 15 count[s2.charAt(i) - 'a'] --; 16 } 17 18 for(int i = 0; i < 26; i++){ 19 if(count[i] != 0){ 20 return false; 21 } 22 } 23 24 if(len1 == 1 && len2 == 1){ 25 return true; 26 } 27 28 for(int i = 1; i < len1; i++){ 29 boolean result = isScramble(s1.substring(0,i), s2.substring(0, i)) && 30 isScramble(s1.substring(i), s2.substring(i)); 31 32 result = result || (isScramble(s1.substring(0, i), s2.substring(len2 - i)) && 33 isScramble(s1.substring(i), s2.substring(0, len2 - i))); 34 35 if(result){ 36 return result; 37 } 38 } 39 return false; 40 }
2.DP
http://blog.sina.com.cn/s/blog_b9285de20101gy6n.html
http://fisherlei.blogspot.com/2013/01/leetcode-scramble-string.html
http://tech-wonderland.net/blog/leetcode-scramble-string.html