Leetcode 87. 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.

题意:一个字符串可被视为由一棵树构成,如果交换任意非叶子节点的两个子节点,得到的字符串就是原字符串的一个scramble。
比如:cat可以可做c/at,如果交换at,会得到c/ta,交换c/at会得到at/c。
一开始,我也有这种疑惑,一个字符串的所有组合应该都是它的scramble,但是字符串长度多于4的时候会得到反例。比如abcde无法通过scramble得到caebd。

思路:考虑一个字符串s如果在某个位置被分为两半s1和s2,而另一个字符串k就是在此位置和s相匹配的。那么要么k1和s1、k2和s2都满足scramble,要么k1和s2、k2和s1是scramble。对于所有可将s分为两段的点,都用上面方法判断,如果有一个位置满足,那么s和k就是scramble,否则,就不是。

public boolean isScramble(String s1, String s2) {
    if (s1 == null || s2 == null || s1.length() != s2.length()) {
        return false;
    }
    if (s1.equals(s2)) {
        return true;
    }

    int[] letters = new int[26];
    for (int i=0; i<s1.length(); i++) {
        letters[s1.charAt(i)-'a']++;
        letters[s2.charAt(i)-'a']--;
    }
    for (int i=0; i<26; i++) if (letters[i]!=0) return false;

    int len = s1.length();
    for (int i = 1; i < len; i++) {
        String s1left = s1.substring(0, i);
        String s1right = s1.substring(i);
        String s2left = s2.substring(0, len - i);
        String s2right = s2.substring(len - i);
        if (isScramble(s1left, s2right) && isScramble(s1right, s2left)) {
            return true;
        }
        if (isScramble(s1left, s2.substring(0, i)) && isScramble(s1right, s2.substring(i))) {
            return true;
        }
    }

    return false;
}

letters这部分前置判断,自己做的是没有想到,leetcode就提示超时了。这部分是一个很好的剪枝,在s和k长度相同的情况下,可以过滤掉绝大部分不匹配的情况。

    原文作者:ShutLove
    原文地址: https://www.jianshu.com/p/8b0d3b5a7aa9
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞