算法:动态规划(一)

字符串解码
题目要求:
一个包含字母的消息被加密之后变成了一个只包含数字的字符串,但是我们现在知道加密的规则:
‘A’ -> 1 ‘B’ -> 2

‘Y’ -> 25 ‘Z’ -> 26
现在给定一个已经被加密的只包含数字的字符串,求出该字符串有多少种被解密的方法。例如 ‘12′ -> AB,或者’12’ -> L.

用C#实现的效果:

《算法:动态规划(一)》 image.png

接下来是用C#实现的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace test {
    class Program {
        const int COUNT = 8;
        /// <summary>
        /// 是否考虑字符串中有数字的可能
        /// 是为2 否为1
        /// </summary>
        public static int SINGLE = 1;
        static void Main(string[] args) {
            if(SINGLE == 1)
                Console.WriteLine("不考虑数字模式");
            else
                Console.WriteLine("考虑数字模式");
            while (true) {
                Console.WriteLine("请输入字符串:");
                string msg = Console.ReadLine();
                Console.WriteLine("输入的字符串为:" + msg);
                string encMsg = Encryption(msg);
                Console.WriteLine("加密后为:" + encMsg);

                var temp = Decryption(encMsg);
                Console.WriteLine("有" + temp + "种可能");
            }
            Console.ReadLine();
        }

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="message">需要加密的字符串</param>
        static string Encryption(string message){
            StringBuilder sbResult = new StringBuilder();

            //  处理每个字节
            foreach (var c in message) {
                if (c >= 65 && c <= 90)
                    sbResult.Append(c - 64);
                else if (c >= 97 && c <= 122)
                    sbResult.Append(c - 96);
                else
                    sbResult.Append(c);
            }
            return sbResult.ToString();
        }

        /// <summary>
        /// 数字转对应字母
        /// 如:1 -> A
        /// </summary>
        /// <param name="i"></param>
        /// <returns></returns>
        static char SerialNumToLetter(int i) {
            return (char)(96+i);
        }

        /// <summary>
        /// 解密
        /// </summary>
        static int Decryption(string str){
            int result =0;
            for (int i = 1; i < str.Length; i++) {      //  以加密后的字符串中的字符为单位循环向后计算
                int ic1 = int.Parse(str[i - 1].ToString()), ic2 = int.Parse(str[i].ToString());
                if (result == 0) {      //  第一次执行则直接加上可能的数目
                    result += SINGLE;
                    if (ic1 * 10 + ic2 <= 27) {
                        result++;
                    }
                } else {        //  非第一次执行则将之前的数目乘以当前数目
                    int t = SINGLE;
                    if (ic1 * 10 + ic2 <= 27) {
                        t++;
                    }
                    result *= t;
                }
            }
            return result;
        }

    }
}
    原文作者:没了帽子的Link
    原文地址: https://www.jianshu.com/p/7066efaf4bc4
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞