TypechoJoeTheme

IT技术分享

统计

[LeetCode 87] Scramble String [Java]

2017-11-04
/
0 评论
/
721 阅读
/
正在检测是否收录...
11/04

1. Description

Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively.

2. Example

Below is one possible representation of s1 = "great":

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".

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".

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.

3. Code

import java.util.Arrays;

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

        if (s1.length() == 1 && s2.length() == 1) {
            if (s1.equals(s2)) {
                return true;
            } else {
                return false;
            }
        }
        return isScrambleDFS(s1, s2);
    }

    private boolean isScrambleDFS(String s1, String s2) {
        if (s1.length() == 1) {
            return true;
        }
        if (!isContainsSame(s1, s2)) {
            return false;
        }

        for (int i = 1; i < s1.length(); i++) {
            String s1Left = s1.substring(0, i);
            String s1Right = s1.substring(i);
            String s2Left = s2.substring(0, i);
            String s2Right = s2.substring(i);
            if (isScrambleDFS(s1Left, s2Left) && isScrambleDFS(s1Right, s2Right)) {
                return true;
            }

            s2Left = s2.substring(0, s2.length() - i);
            s2Right = s2.substring(s2.length() - i);
            if (isScrambleDFS(s1Left, s2Right) && isScrambleDFS(s1Right, s2Left)) {
                return true;
            }
        }
        return false;
    }

    private boolean isContainsSame(String s1, String s2) {
        char[] array1 = s1.toCharArray();
        char[] array2 = s2.toCharArray();
        Arrays.sort(array1);
        Arrays.sort(array2);
        for (int i = 0; i < array1.length; i++) {
            if (array1[i] != array2[i]) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        LeetCode0087 leetcode = new LeetCode0087();
        System.out.println(leetcode.isScramble("great", "rgtae"));
    }
}
Tree
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/1223/(转载时请注明本文出处及文章链接)