爬行字符串判断

题目描述

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

Below is one possible representation ofs1="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 stringss1ands2of the same length,  determine ifs2is a scrambled string ofs1.

这道题定义了一种爬行字符串,就是说假如把一个字符串当做一个二叉树的根,然后它的非空子字符串是它的子节点,然后交换某个子字符串的两个子节点,重新爬行回去形成一个新的字符串,这个新字符串和原来的字符串互为爬行字符串。这道题可以用递归Recursion或是动态规划Dynamic Programming来做,我们先来看递归的解法,参见网友uniEagle的博客简单的说,就是s1和s2是scramble的话,那么必然存在一个在s1上的长度l1,将s1分成s11和s12两段,同样有s21和s22.那么要么s11和s21是scramble的并且s12和s22是scramble的;要么s11和s22是scramble的并且s12和s21是scramble的。就拿题目中的例子 rgeat 和 great 来说,rgeat 可分成 rg 和 eat 两段, great 可分成 gr 和 eat 两段,rg 和 gr 是scrambled的, eat 和 eat 当然是scrambled。

题意在于判断一个字符串是否为另一个字符串“乱序”得到,这种乱序采用的方式是将一个字符串从某个位置“割开”,形成两个子串,然后对两个子串进行同样的“割开”操作,直到到达叶子节点,无法再分割。然后对非叶子节点的左右孩子节点进行交换,最后重新从左至右组合形成新的字符串,由于这个过程中存在字符位置的变化,因此,原来的字符串顺序可能会被打乱,当然也可能没有(同一个非叶子节点的左右孩子交换0次或偶数次,就无变化)。


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容