首页 | 新闻 | 新品 | 文库 | 方案 | 视频 | 下载 | 商城 | 开发板 | 数据中心 | 座谈新版 | 培训 | 工具 | 博客 | 论坛 | 百科 | GEC | 活动 | 主题月 | 电子展
返回列表 回复 发帖

爬行字符串判断

爬行字符串判断

题目描述

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次或偶数次,就无变化)。
返回列表