递归求解kitty猫的基因编码

来源:互联网 发布:dns 端口号 编辑:程序博客网 时间:2024/05/18 17:42

题目来源: http://www.programfan.com/acm/show.asp?qid=77

 

题目信息 :

kitty猫的基因编码

Problem
kitty的基因编码如下定义: kitty的基因由一串长度2^k(k<=8)的01序列构成,为了方便研究,需要把,01序列转换为ABC编码。用T(s)来表示01序列s的ABC编码 T(s)=‘A'(当S全由'0'组成) T(s)=‘B'(当s全由'1'组成) T(s)=‘C'+T(s1)+T(s2) s1,s2为把s等分为2个长度相等的子串 比如 T('00')='A' T('00001111')='CAB'

Input
一行,长度为2^k,为kitty猫的01基因编码,有多个数据

Output
一行,由ABC构成的ABC编码

Sample Input
01001011

Sample Output
CCCABACCBAB

 

思路见注释,很容易明白。

 

代码如下:

#include <iostream>#include <string>using namespace std;bool allthesame(string s)//比较一个string中是不是只有一个类型的字符{    if(s.length()==1)    return true;    for(int i=1;i<s.length();i++)    {        if(s.substr(i,1).compare(s.substr(i-1,1)))            return false;    }    return true;}string temp;string decodeDNA(string dnastr)//递归的办法 ,很容易理解{    if(!allthesame(dnastr))    {        temp="C"+decodeDNA(dnastr.substr(0,dnastr.length()/2))+decodeDNA(dnastr.substr(dnastr.length()/2,dnastr.length()/2));    }    else    {        if(!dnastr.substr(0,1).compare("0"))            temp="A";        else            temp="B";    }    return temp;}int main(){    string DNA;    cout<<"请输入基因编码"<<endl;    cin>>DNA;    decodeDNA(DNA);    cout<<temp<<endl;       return 0;}

 

值得注意的是:

1.#include <string> 可以直接用库函数, 不必要写比较或其他小的函数。

2.在进行字符串连接时 ,string 类型直接“”+即可。

原创粉丝点击