Scramble String

http://www.lintcode.com/en/problem/scramble-string/?rand=true

import java.util.Arrays;

public class Solution {
    /*
     * @param s1: A string
     * @param s2: Another string
     * @return: whether s2 is a scrambled string of s1
     */
    public boolean isScramble(String s1, String s2) {
        // write your code here
        if (s1 == s2) {
            return true;
        }
        if (s1.length() != s2.length()) {
            return false;
        }
        if (s1.length() == 0 || s1.equals(s2)) {
            return true;
        }
        char[] a = s1.toCharArray();
        Arrays.sort(a);
        char[] b = s2.toCharArray();
        Arrays.sort(b);
//        两个字符串的字符不相同,直接返回
        if (!Arrays.equals(a, b)) {
            return false;
        }
        for (int i = 1; i < s1.length(); i++) {
//            把s1分成两部分,
            String s11 = s1.substring(0, i);
            String s12 = s1.substring(i, s1.length());
//            s2有两种分法,一是和s1相同的分法,一个是反方向的分法。
            String s21 = s2.substring(0, i);
            String s22 = s2.substring(i, s1.length());
            String s23 = s2.substring(s1.length() - i, s1.length());
            String s24 = s2.substring(0, s1.length() - i);
//            递归,如果这两个恰好都符合条件,那么它本身也符合条件。
            if (isScramble(s11, s21) && isScramble(s12, s22)) {
                return true;
            }
            if (isScramble(s11, s23) && isScramble(s12, s24)) {
                return true;
            }
        }
        return false;
    }
}

你可能感兴趣的:(Scramble String)