zoukankan      html  css  js  c++  java
  • String Reduction问题分析

    问题描述:

    Given a string consisting of a,b and c's, we can perform the following operation: Take any two adjacent distinct characters and replace it with the third character. For example, if 'a' and 'c' are adjacent, they can replaced with 'b'. What is the smallest string which can result by applying this operation repeatedly?

    翻译:

    给定一个由a/b/c构成的字符串,你可以把相邻且不同的两个字符替换为剩下的那一个字符,比如你可以把字符串中的‘ab’替换为‘c’。求通过不断的替换操作,最后能得到的字符串的最小长度是多少?

    Sample Input


    cab 
    bcab 
    ccccc

    Sample Output



    5

    样例解释:

    cab -> cc or cab -> bb

    bcab -> aab -> ac -> b

    ccccc 不可变

    解答:

    这个问题的答案让人拍手称快. 分为三种情况:

    首先,如果字符串中字符全部一样,那么直接返回该字符串的长度即可.

    其次,如果三种字符的个数都是奇数或者都是偶数,那么答案为2

    其他情况,返回1.

    正确性证明:(数学归纳法),N表示字符串的长度

    首先,N=3的时候.如果字符都相同,返回3;如果都不同返回2,其他情况返回1.

    其次,当N>3的时候,如果字符串中字符不是全部相同的话,我们可以利用替换法则获得长度为N-1的串,且该串也不是由相同字符组成的

    还有一个规律,那就是字符个数全为奇数的串经过转换就变成字符个数全为偶数的串,反之亦然。

  • 相关阅读:
    cygwin 下配置ssh
    使用MarsEdit写博客
    bash no job control in this shell
    安装devtoolset-2:因由安装gcc 4.8而引起
    AFNetworking Property with 'retain (or strong)' attribute must be of object type
    从xib 创建 collectionViewCell
    CocoaPods 安装
    个人理解的 Https 通信流程
    cellforrowatindexpath 不执行 的原因
    do{} while(0) 的意义和用法
  • 原文地址:https://www.cnblogs.com/Tinamei/p/4796756.html
Copyright © 2011-2022 走看看