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; }
- leetCode练习(87)
- leetCode练习(7)
- leetCode练习(9)
- leetCode练习(2)
- leetCode练习(14)
- leetCode练习(3)
- leetCode练习(4)
- leetCode练习(19)
- leetCode练习(18)
- leetCode练习(5)
- leetCode练习(15)
- leetCode练习(20)
- leetCode练习(21)
- leetCode练习(16)
- leetCode练习(17)
- leetCode练习(11)
- leetCode练习(24)
- leetCode练习(22)
- 第八周 OJ总结<2>-C语言实验——分数序列
- [AHK]同花顺的委托下单界面的密码自动填写脚本
- windows安装memcached
- Linux命令合集
- 12306在线买火车票为什么需要安装根证书
- leetCode练习(87)
- Java反射与代理
- 判断 checkbox 是否选中以及 设置checkbox选中
- 求二进制数中1的个数
- ASP.NET 中点击按钮时邮件自动发送功能实例
- JAVA是值传递还是引用传递
- leetcode 112. Path Sum
- C#中值类型和引用类型及类型的转换
- SlidingMenu关闭手势滑动