zoukankan      html  css  js  c++  java
  • 利用递归获取字符串有多少种转化可能(从左到右)

    1.c实现

     1 #include<stdio.h>
     2 #include<stdlib.h>
     3 #include<string.h>
     4 //从左往右的尝试
     5 //规定1和A对应,2和B对应、3和C对应...那么一个数字字符串比如”111“
     6 //就可以转化为”AAA” 、“KA”和“AK”
     7 
     8 //给定一个只有数字字符组成的字符串str,返回有多少种转化结果
     9 int process(char *str, int i){
    10     if(i==strlen(str))
    11        return 1;
    12 
    13     //i没有到终止位置
    14     if(str[i]=='0'){
    15         return 0;
    16     }
    17     //str[i]字符不是‘0’
    18     if(str[i]=='1'){
    19         int res = process(str,i+1);//i自己作为单独的部分,后续有多少种方法
    20         if((i+1)<strlen(str))
    21             res += process(str,i+2); //(i和i+1)作为单独的部分,后续有多少种方法
    22         return res;
    23     }
    24     if(str[i]=='2'){
    25        int res = process(str,i+1);//i自己作为单独的部分,后续有多少种方法
    26        //(i和i+1)作为单独的部分并且没有超过26,后续有多少种方法
    27        if((i+1)<strlen(str) && (str[i+1]>='0' && str[i+1]<='6')){
    28            res += process(str,i+2);
    29        }
    30        return res;
    31     }
    32     //str[i] == '3' ~ '9'
    33     return process(str,i+1);
    34 }
    35 
    36 int main(){
    37    char* str = malloc(sizeof(char)*8);
    38    printf("请输入数字字符串:");
    39    scanf("%s",str);
    40    char* ch={'A','B','C','D','E','F','G','H','I','J','K','L','M','N',
    41            'O','P','Q','R','S','T','U','V','W','X','Y','Z'};
    42    int res = process(str,0);
    43    printf("%d",res);
    44    //char c;
    45   // while((c=process(str,0))!= '0'){
    46      // printf(ch);
    47    //}
    48    return 0;
    49 }
  • 相关阅读:
    A1052. Linked List Sorting (25)
    A1032. Sharing (25)
    A1022. Digital Library (30)
    A1071. Speech Patterns (25)
    A1054. The Dominant Color (20)
    A1060. Are They Equal (25)
    A1063. Set Similarity (25)
    电子码表
    矩阵键盘
    对象追踪、临时对象追踪、绝对坐标与相对坐标
  • 原文地址:https://www.cnblogs.com/indifferent/p/14396797.html
Copyright © 2011-2022 走看看