題目: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 representa...
題目:
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.
思路:
遞歸,isScramble(S1[0, i], S2[0, i]) && isScramble(S1[i, N], S2[i, N])或者isScramble(S1[0, i], S2[N-i, N]) && isScramble(S1[i, N], S2[0, i])。判斷時儘早返回,比如長度不一,或者兩個字元串內的字元出現的頻率不一樣。
package recursion; import java.util.Arrays; public class ScrambleString { public boolean isScramble(String s1, String s2) { int m = s1.length(); int n = s2.length(); if (m != n) return false; char[] c1 = s1.toCharArray(); char[] c2 = s2.toCharArray(); Arrays.sort(c1); Arrays.sort(c2); if (!isEqual(c1, c2, m)) return false; if (m == 1) return true; for (int i = 1; i < m; ++i) { if (isScramble(s1.substring(0, i), s2.substring(0, i)) && isScramble(s1.substring(i, m), s2.substring(i, m))) return true; if (isScramble(s1.substring(0, i), s2.substring(m - i, m)) && isScramble(s1.substring(i, m), s2.substring(0, m - i))) return true; } return false; } private boolean isEqual(char[] c1, char[] c2, int n) { for (int i = 0; i < n; ++i) { if (c1[i] != c2[i]) return false; } return true; } public static void main(String[] args) { // TODO Auto-generated method stub ScrambleString s = new ScrambleString(); System.out.println(s.isScramble("rgtae", "great")); } }