leetCode练习(87)

来源:互联网 发布:网络推广做什么的 编辑:程序博客网 时间:2024/05/17 08:52

题目:Scramble String

难度:hard

问题描述:

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 ifs2 is a scrambled string of s1.

解题思路:

使用递归加剪枝的方法。例str1=“123”和str2=“231”,先判断str1和str2是不是字符能够对应,不能则返回false,然后将str1依次拆为(“1”,“23”)和(“12“,”3“),判断”1“和str2中的“”2“是不是scramble关系,”23“和str2中的”31“是不是scramble关系,或者”1“和”31“、”23“和”2“是不是scrabble关系。满足了则返回true。参考了doc_sgl的文章。

具体代码如下:

public static boolean isScramble(String s1, String s2) {        if(s1.length()!=s2.length()){        return false;        }        if(s1.equals(s2)){        return true;        }        int[] temp=new int[26];        for(int i=0;i<s1.length();i++){        temp[s1.charAt(i)-'a']++;        }        for(int i=0;i<s2.length();i++){        temp[s2.charAt(i)-'a']--;        }        for(int i=0;i<26;i++){        if(temp[i]!=0){        return false;        }        }        for(int i=1;i<s1.length();i++){        boolean result=isScramble(s1.substring(0, i),s2.substring(0, i))&&isScramble(s1.substring(i),s2.substring(i));        result=result||isScramble(s1.substring(0, i),s2.substring(s2.length()-i))&&isScramble(s1.substring(i),s2.substring(0,s2.length()-i));        if(result) return true;        }        return false;    }




0 0
原创粉丝点击