LeetCode 87. Scramble String

来源:互联网 发布:手机麻将源码带房卡 编辑:程序博客网 时间:2024/06/07 09:35

题目链接

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.

解:

"rgtae"是"great"的一个scrambled string,"eat"也是"tae"的一个scrambled string,可见由great到rgtae,根结点左右子树未交换,从eat到tae,根结点左右子树发生交换,从这里分成2种情况:

判断两个string是不是互为scrambled string时:

1)s1前面长度i子串和s2前面长度i子串互为scrambled string && s1剩下部分串和s2剩下部分串互为scrambled string

2)s1前面长度i子串和s2后面长度i子串互为scrambled string && s1剩下部分串和s2剩下部分串互为scrambled string


遍历子串,递归,即得到结果,为提高效率,实现sameLetters函数,用以判断2个串的字符是否完全相同,毕竟字符完全相同才可能互为scrambled string,先对子串sameLetters检查,若满足再进行子串isScramble的检查,代码:

class Solution {public:    //2个string是否含有完全相同的字母    bool sameLetters(string a, string b) {        int len = a.size();        int aa[26] = {0};        int bb[26] = {0};        for (int i = 0; i < len; i++) {            aa[a[i]-'a']++;            bb[b[i]-'a']++;        }        for (int i = 0; i < 26; i++)             if (aa[i] != bb[i]) return false;        return true;    }    bool isScramble(string s1, string s2) {        int len1 = s1.length();        int len2 = s2.length();        if (len1 != len2) return false;        if (s1 == s2) return true;        for (int i = 1; i < len1; i++) {            string sub1Head = s1.substr(0, i);            string sub1Tail = s1.substr(len1-i, i);            string sub2Head = s2.substr(0, i);            if (sameLetters(sub1Head, sub2Head))                if (isScramble(sub1Head, sub2Head) && isScramble(s1.substr(i, len1-i), s2.substr(i, len1-i))) return true;            if (sameLetters(sub2Head, sub1Tail))                 if (isScramble(sub2Head, sub1Tail) && isScramble(s2.substr(i, len1-i), s1.substr(0, len1-i))) return true;        }        return false;    }};



原创粉丝点击