*leetcode #87 in cpp
来源:互联网 发布:php 上传图片到七牛 编辑:程序博客网 时间:2024/05/18 00:20
Solution:
Since the scramble is made by constructing a binary tree and swapping them randomly, we could consider what property is in this construction.
Property 1 : Suppose l is the left tree and r is the right tree, l would be either at left of r or at right of r in the scramble.
Say 'great' and the partition point is 'r', then l = 'gr' and r = 'eat'.
the scramble could be 'eatgr' or 'great', where l is at the right or left of r.
But l would never be mixed among r. Say 'egart' is not the scramble given the partition point is 'r'.
Property 2: if A(left tree is al, right tree is ar) is a scramble of B(left tree is bl, right tree is br), then either 1. al is scramble of bl and ar is the scramble of br or 2. al is the scramble of br and ar of bl.
This property is a result of property 1.
Thus to see if a string is a scramble of another string, we try to find a partition point and see if the left tree and right tree are scramble of the ones of another string. Note that this is a recurrent structure.
Code:
class Solution {public: bool isScramble(string s1, string s2) { int sublen; int len = s1.length(); if(len == 1) return s1[0] == s2[0]; if(len == 2){ return (s1[1] == s2[0] && s1[0] == s2[1]) || (s1[1]== s2[1] && s1[0] == s2[0]); } string temp1 = s1; string temp2 = s2; sort(temp1.begin(), temp1.end()); sort(temp2.begin(), temp2.end()); if(temp1!=temp2) return false; //two cases string 1 is scramble of s2. //1. s1's left is scramble of s2's right and s1's right is scramble of s2's left //2. s1's left is scramble of s2's left and s1's right is scramble of s2's right for(sublen = 1; sublen < len; sublen++){//make partition point //compare [aaa bbbb] to [aaa bbbb] if(isScramble(s1.substr(0,sublen), s2.substr(0,sublen)) && isScramble(s1.substr(sublen, len-sublen), s2.substr(sublen, len-sublen))) return true; //copare [aaa bbbb] to [bbbb aaa] if(isScramble(s1.substr(0, sublen), s2.substr(len-sublen, sublen)) && isScramble(s1.substr(sublen, len - sublen), s2.substr(0,len - sublen))) return true; } return false; } };
- *leetcode #87 in cpp
- leetcode #12 in cpp
- Leetcode #13 in cpp
- Leetcode #14 in cpp
- leetcode %15 in cpp
- leetcode #16 in cpp
- leetcode #17 in cpp
- leetcode #18 in cpp
- leetcode #20 in cpp
- leetcode #21 in cpp
- leetcode #22 in cpp
- leetcode #23 in cpp
- leetcode #24 in cpp
- leetcode #25 in cpp
- leetcode #26 in cpp
- leetcode #27 in cpp
- leetcode #28 in cpp
- leetcode #29 in cpp
- org.xml.sax.SAXParseException: Failed to read schema document错误的完美解决方法 以及 Spring如何加载XSD文件
- DAG的深度优先搜索标记
- 以Rust为例,看如何学习一门新语言?
- DX学习笔记(旋转的茶壶)DX自带几何体
- LeetCode 163. Missing Ranges
- *leetcode #87 in cpp
- 常用的一些HQL查询语句详解(1)
- Win7+VS2013+OpenCV2.4.13+CUDA7.5.18+CMAKE3.3.0 环境搭建
- leetcode #88 in cpp
- LeetCode 166. Fraction to Recurring Decimal
- 数据库的内联接、外联接
- Binary Tree Level Order Traversal II
- C/C++中读写文件
- leetcode #89 in cpp