LeetCode087 Scramble String

来源:互联网 发布:java jdbc mysql 编辑:程序博客网 时间:2024/05/22 11:43

详细见:leetcode.com/problems/scramble-string


Java Solution: github

package leetcode;import java.util.HashMap;/* * 87. Scramble String  QuestionEditorial Solution  My SubmissionsTotal Accepted: 52267Total Submissions: 189615Difficulty: HardGiven 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   tTo 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   tWe 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   aWe 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. *//* * 两个相邻交换: * abcde * bacde * acbde * abdce * abced *  *  */public class P087_ScrambleString {public static void main(String[] args) {System.out.println(new Solution2().isScramble("abb", "bba"));System.out.println(new Solution2().isScramble("abb", "bab"));System.out.println(new Solution2().isScramble("abb", "abb"));System.out.println(new Solution2().isScramble("rea", "rae"));System.out.println(new Solution2().isScramble("great", "traeg"));System.out.println(new Solution2().isScramble("great", "ragte"));System.out.println(new Solution2().isScramble("hobobyrqd", "hbyorqdbo"));System.out.println(new Solution2().isScramble("obyrqd", "yorqdb"));System.out.println(new Solution2().isScramble("obym", "yomb"));}/* * WA */static class Solution {char[] c1 = null, c2 = null;HashMap<Character, Integer> m3 = new HashMap<>();public boolean isScramble(String s1, String s2) {if (s1 == null || s2 == null)return s1 == s2;if (s1.length() != s2.length())return false;if (s1.length() == 0)return true;c1 = s1.toCharArray();c2 = s2.toCharArray();return judge(0, c1.length - 1, 0, c2.length - 1);}private boolean judge(int sti1, int eni1, int sti2, int eni2) {if (sti1 - eni1 != sti2 - eni2)return false;if (sti1 > eni1) {return false;} else if (sti1 == eni1) {return c1[sti1] == c2[sti2];} else if (sti1 + 1 == eni1) {return (c1[sti1] == c2[sti2] && c1[eni1] == c2[eni2]) || (c1[sti1] == c2[eni2] && c1[eni1] == c2[sti2]);}m3.clear();int i = eni1 - sti1;for (; i > -1; i--) {char c = c1[sti1 + i];if (m3.containsKey(c)) {int c1_val = m3.get(c);if (c1_val == -1) {m3.remove(c);} else {m3.put(c, c1_val + 1);}} else {m3.put(c, 1);}c = c2[sti2 + i];if (m3.containsKey(c)) {int c2_val = m3.get(c);if (c2_val == 1) {m3.remove(c);} else {m3.put(c, c2_val - 1);}} else {m3.put(c, -1);}if (m3.size() == 0)break;}if (-1 == i)return false;if (0 == i) {m3.clear();int j = 0;for (; j <= eni1 - sti1; j++) {char c = c1[sti1 + j];if (m3.containsKey(c)) {int c1_val = m3.get(c);if (c1_val == -1) {m3.remove(c);} else {m3.put(c, c1_val + 1);}} else {m3.put(c, 1);}c = c2[sti2 - j + eni1 - sti1];if (m3.containsKey(c)) {int c2_val = m3.get(c);if (c2_val == 1) {m3.remove(c);} else {m3.put(c, c2_val - 1);}} else {m3.put(c, -1);}if (m3.size() == 0)break;}if (j > eni1 - sti1) {return false;} else if (j == eni1 - sti1) {if (c1[sti1] != 'o' || c2[sti2] != 'y')return false;char temp = c1[sti1];c1[sti1] = c1[eni1];c1[eni1] = temp;return judge(sti1, eni1, sti2, eni2);}return judge(sti1, sti1 + j, eni2 - j, eni2) && judge(sti1 + j + 1, eni1, sti2, eni2 - j - 1);}return judge(sti1 + i, eni1, sti2 + i, eni2) && judge(sti1, sti1 + i - 1, sti2, sti2 + i - 1);}}/* * WA */static class Solution2 {char[] c1 = null, c2 = null;HashMap<Character, Integer> map = new HashMap<>();public boolean isScramble(String s1, String s2) {if (s1 == null || s2 == null)return s1 == s2;if (s1.length() != s2.length())return false;if (s1.length() == 0)return true;c1 = s1.toCharArray();c2 = s2.toCharArray();return judge(0, c1.length - 1, 0, c2.length - 1);}private boolean judge(int sti1, int eni1, int sti2, int eni2) {if (sti1 - eni1 != sti2 - eni2)return false;if (sti1 > eni1) {return false;} else if (sti1 == eni1) {return c1[sti1] == c2[sti2];} else if (sti1 + 1 == eni1) {return (c1[sti1] == c2[sti2] && c1[eni1] == c2[eni2]) || (c1[sti1] == c2[eni2] && c1[eni1] == c2[sti2]);}map.clear();int i = eni1 - sti1;for (; i > -1; i--) {char c = c1[sti1 + i];if (map.containsKey(c)) {int c1_val = map.get(c);if (c1_val == -1) {map.remove(c);} else {map.put(c, c1_val + 1);}} else {map.put(c, 1);}c = c2[sti2 + i];if (map.containsKey(c)) {int c2_val = map.get(c);if (c2_val == 1) {map.remove(c);} else {map.put(c, c2_val - 1);}} else {map.put(c, -1);}}if (map.size() != 0)return false;for (int j = 0; j < eni1 - sti1; j++) {if ((judge(sti1, sti1 + j, sti2, sti2 + j) && judge(sti1 + j + 1, eni1, sti2 + j + 1, eni2))|| (judge(sti1, sti1 + j, eni2 - j, eni2) && judge(eni1 - j, eni1, sti2, sti2 + j)))return true;}return false;}}/* * AC * 23 ms */static class Solution3 {public boolean isScramble(String s1, String s2) {int len = s1.length();if (len != s2.length()) {return false;}if (len == 0) {return true;}char[] c1 = s1.toCharArray();char[] c2 = s2.toCharArray();boolean[][][] result = new boolean[len][len][len];for (int i = 0; i < len; ++i) {for (int j = 0; j < len; ++j) {result[0][i][j] = (c1[i] == c2[j]);}}for (int k = 2; k <= len; ++k) {for (int i = len - k; i >= 0; --i) {for (int j = len - k; j >= 0; --j) {boolean r = false;for (int m = 1; m < k && !r; ++m) {r = (result[m - 1][i][j] && result[k - m - 1][i + m][j + m])|| (result[m - 1][i][j + k - m] && result[k - m - 1][i + m][j]);}result[k - 1][i][j] = r;}}}return result[len - 1][0][0];}}}


C Solution: github

/*    url: leetcode.com/problems/scramble-string    AC 3ms 50.00%*/#include <stdio.h>#include <stdlib.h>#include <string.h>#define bool intbool equals(char* s1, int i1, int j1, char* s2, int i2, int j2) {    int k = 0;    if (j1 - i1 != j2 - i2 || i1 > j1) return 0;    for (k = j1-i1; k > -1; k --)        if (s1[i1+k] != s2[i2+k]) return 0;    return 1;}bool search(char* s1, int i1, int j1, char* s2, int i2, int j2, int* m) {    int i = 0;    if (equals(s1, i1, j1, s2, i2, j2)) return 1;    for (i = 0; i < 26; i ++) m[i] = 0;    for (i = i1; i <= j1; i ++) m[s1[i]-'a'] ++;    for (i = i2; i <= j2; i ++) {        m[s2[i] - 'a'] --;        if (m[s2[i] - 'a'] < 0) return 0;     }    for (i = j1-i1-1; i > -1; i --) {        if (search(s1, i1, i1+i, s2, i2, i2+i, m) &&             search(s1, i1+i+1, j1, s2, i2+i+1, j2, m)) return 1;        if (search(s1, i1, i1+i, s2, j2-i, j2, m) &&             search(s1, i1+i+1, j1, s2, i2, j2-i-1, m)) return 1;    }    return 0;}bool isScramble(char* s1, char* s2) {    int j1 = s1 == NULL ? -1 : strlen(s1)-1;    int j2 = s2 == NULL ? -1 : strlen(s2)-1;    int i1 = 0, i2 = 0, m[26];    if (j1 < 0 || j2 < 0) return j1 == j2;    return search(s1, i1, j1, s2, i2, j2, m);}int main() {    char* s1 = "abc";    char* s2 = "cba";    printf("answer is %d\r\n", isScramble(s1, s2));    return 0;}


Python Solution: github

#coding=utf-8'''    url: leetcode.com/problems/scramble-string    @author:     zxwtry    @email:      zxwtry@qq.com    @date:       2017年4月21日    @details:    Solution: 95ms 60.64%'''class Solution(object):    def search(self, s1, i1, j1, n1, s2, i2, j2, n2):        m, e = {}, True        for k in range(j1-i1+1):            e = s1[i1+k] == s2[i2+k]            if not e: break        if e: return True        for k in range(i1, j1+1):            s = s1[k]            if s in m: m[s] = m[s]+1            else: m[s] = 1        for k in range(i2, j2+1):            if s2[k] not in m or m[s2[k]] <= 0:                return False            m[s2[k]] = m[s2[k]]-1        for k in range(j1-i1):            if self.search(s1, i1, i1+k, n1, s2, j2-k, j2, n2) \                and self.search(s1, i1+k+1, j1, n1, s2, i2, j2-k-1, n2):                return True            if self.search(s1, i1, i1+k, n1, s2, i2, i2+k, n2) \                and self.search(s1, i1+k+1, j1, n1, s2, i2+k+1, j2, n2):                return True        return False                    def isScramble(self, s1, s2):        """        :type s1: str        :type s2: str        :rtype: bool        """        n1 = 0 if s1 == None else len(s1)        n2 = 0 if s2 == None else len(s2)        if n1 != n2: return False        return self.search(s1, 0, n1-1, n1, s2, 0, n2-1, n2)    if __name__ == "__main__":    m = [            "a",            "great",            "great",            "great",            "abc",            "abcdefghijklmn",            "oatzzffqpnwcxhejzjsnpmkmzngneo"        ]    n = [            "b",            "rgeat",            "rgtae",            "eatgr",            "cba",            "efghijklmncadb",            "acegneonzmkmpnsjzjhxwnpqffzzto"        ]    for i in range(len(m)):        print(Solution().isScramble(m[i], n[i]))


0 0
原创粉丝点击