博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Scramble String
阅读量:5135 次
发布时间:2019-06-13

本文共 2326 字,大约阅读时间需要 7 分钟。

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.

1 public class Solution { 2     /** 3      * @param s1 A string 4      * @param s2 Another string 5      * @return whether s2 is a scrambled string of s1 6      */ 7     public boolean isScramble(String s1, String s2) { 8         if (s1.length() != s2.length()) return false; 9         10         if (s1.equals(s2)) return true;11         12         if (!isValid(s1, s2)) {13             return false;14         }15         16         for (int i = 1; i < s1.length(); i++) {17             String s11 = s1.substring(0, i);18             String s12 = s1.substring(i);19             20             String s21 = s2.substring(0, i);21             String s22 = s2.substring(i);22             23             String s23 = s2.substring(0, s2.length() - i);24             String s24 = s2.substring(s2.length() - i);25             26             if (isScramble(s11, s21) && isScramble(s12, s22) || isScramble(s11, s24) && isScramble(s12, s23)) {27                 return true;28             }29         }30         return false;31     }32     33     private boolean isValid(String s1, String s2) {34         char[] arr1 = s1.toCharArray();35         char[] arr2 = s2.toCharArray();36         Arrays.sort(arr1);37         Arrays.sort(arr2);38         if (!(new String(arr1)).equals(new String(arr2))) {39             return false;40         }41         return true;42     }43 }

 

转载于:https://www.cnblogs.com/beiyeqingteng/p/5693500.html

你可能感兴趣的文章
Android设置Gmail邮箱
查看>>
StringBuffer的用法
查看>>
js编写时间选择框
查看>>
PHP压缩文件操作
查看>>
4.你认为一些军事方面的软件系统采用什么样的开发模型比较合适?
查看>>
日常开发需要掌握的Maven知识
查看>>
Java数据结构和算法(四)--链表
查看>>
JIRA
查看>>
ssl介绍以及双向认证和单向认证原理
查看>>
【BZOJ2441】【中山市选2011】小W的问题(树状数组+权值线段树)
查看>>
小技巧——直接在目录中输入cmd然后就打开cmd命令窗口
查看>>
深浅拷贝(十四)
查看>>
由级别和性格特征将程序员分类 ---看看你属于哪一种
查看>>
HDU 6370(并查集)
查看>>
BZOJ 1207(dp)
查看>>
对我来说,只有一件事情是重要的
查看>>
完整的Socket代码
查看>>
PE知识复习之PE的导入表
查看>>
POJ 3280 Cheapest Palindrome
查看>>
HDU 2076 夹角有多大(题目已修改,注意读题)
查看>>