87. Scramble string

Source: Internet
Author: User

Given a stringS1, We may represent it as a binary tree by partitioning it to two non-empty substrings recursively.

Below is one possible representationS1="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"Great".

Similarly, if we continue to swap the children of nodes"Eat"And"", It produces a scrambled string"Rgtae".

 
Rgtae/rg Tae/\/r g ta E/T

We say that"Rgtae"Is a scrambled string"Great".

Given two stringsS1AndS2Of the same length, determine ifS2Is a scrambled stringS1.

Example 1:

 
Input: S1 = "great", S2 = "rgeat" output: True

Example 2:

 
Input: S1 = "ABCDE", S2 = "caebd" output: false

AC code:

Class solution {public: bool isscramble (string S1, string S2) {If (S1 = S2) return true; int Len = s1.length (); vector <int> V (26, 0); For (INT I = 0; I <Len; ++ I) {v [S1 [I]-'a'] ++; V [S2 [I]-'a'] --;} For (INT I = 0; I <26; ++ I) {If (V [I]! = 0) return false;} For (INT I = 1; I <Len; ++ I) {If (isscramble (s1.substr (0, I), s2.substr (0, i) & isscramble (s1.substr (I), s2.substr (I) return true; If (isscramble (s1.substr (0, I), s2.substr (LEN-I )) & isscramble (s1.substr (I), s2.substr (0, len-I) return true ;}return false ;}};

Runtime:0 MS, faster100.00% of C ++ online submissions for scramble string.

 

87. Scramble string

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.