zoukankan      html  css  js  c++  java
  • 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     }
  • 相关阅读:
    LAMP
    监控和安全运维 1.8 zabbix服务端安装
    监控和安全运维 1.7 nagios配置邮件告警
    易道用车-拿什么说爱你
    unix exec族函数 关于参数的疑惑
    关于 Unix 用户权限及进程权限及 Saved set-user-id
    ANSI C中关于FILE流的一些
    Filco minila 的蛋疼。
    IIS32位,64位模式下切换
    Gvim+Emmet.vim 那些事。
  • 原文地址:https://www.cnblogs.com/waruzhi/p/3438730.html
Copyright © 2011-2022 走看看