• Scramble String


    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.

    思路:

    动规。用result[i][j][k]表示s[i..i+k-1]与s[j..j+k-1]是否相等。

    代码:

     1     bool isScramble(string s1, string s2) {
     2         // IMPORTANT: Please reset any member data you declared, as
     3         // the same Solution instance will be reused for each test case.
     4         if(s1.length() != s2.length())
     5             return false;
     6         int len = s1.length();
     7         bool result[len][len][len+1];
     8         memset(result, false, sizeof(bool)*len*len*(len+1));
     9         int i,j,k,m;
    10         for(i = 1; i <= len; i++){
    11             for(j = 0; j <= len-i; j++){
    12                 for(k = 0; k <= len-1; k++){
    13                     if(i == 1)
    14                         result[j][k][i] = (s1[j] == s2[k]);
    15                     else{
    16                         for(m = 1 ; m < i; m++){
    17                             result[j][k][i] = (result[j][k][m] && result[j+m][k+m][i-m])||(result[j][k+i-m][m] && result[j+m][k][i-m]);
    18                             if(result[j][k][i])
    19                                 break;
    20                         }                            
    21                     }
    22                     cout<<j<<" "<<k<<" "<<i<<": "<<result[j][k][i]<<endl;
    23                 }
    24             }   
    25         }
    26         return result[0][0][len];
    27     }
  • 相关阅读:
    devops
    classloader
    webpack之个人理解
    java map
    前端性能资料
    kibana使用的lucene查询语法
    【转】关于JVM CPU资源占用过高的问题排查
    netstat命令
    使用LR11录制手机脚本
    jemeter逻辑控制器
  • 原文地址:https://www.cnblogs.com/waruzhi/p/3438730.html
Copyright © 2020-2023  润新知