You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

数字转字母组合实现求助:给定数字生成所有对应单词

数字转对应单词列表问题

需求说明

字母与数字的映射规则为:a对应1,b对应2,……,z对应26。单词可转换为对应数字的拼接形式,例如:

dog   → 4|15|7  → 4157

现需实现反向操作:给定一个数字,生成所有可能的对应单词列表,例如:

512   → 5|1|2   → eab
        5|12    → el

4157  → 4|1|5|7 → daeg
      → 4|15|7  → dog

现有尝试的C#代码

数据映射类

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

namespace NumberToWords
{
    public class Data
    {
        public IDictionary<int, string> listOfAlphabets;
        public Data()
        {
            listOfAlphabets = new Dictionary<int, string>();
            listOfAlphabets.Add(1, "A");
            listOfAlphabets.Add(2, "B");
            listOfAlphabets.Add(3, "C");
            listOfAlphabets.Add(4, "D");
            listOfAlphabets.Add(5, "E");
            listOfAlphabets.Add(6, "F");
            listOfAlphabets.Add(7, "G");
            listOfAlphabets.Add(8, "H");
            listOfAlphabets.Add(9, "I");
            listOfAlphabets.Add(10, "J");
            listOfAlphabets.Add(11, "K");
            listOfAlphabets.Add(12, "L");
            listOfAlphabets.Add(13, "M");
            listOfAlphabets.Add(14, "N");
            listOfAlphabets.Add(15, "O");
            listOfAlphabets.Add(16, "P");
            listOfAlphabets.Add(17, "Q");
            listOfAlphabets.Add(18, "R");
            listOfAlphabets.Add(19, "S");
            listOfAlphabets.Add(20, "T");
            listOfAlphabets.Add(21, "U");
            listOfAlphabets.Add(22, "V");
            listOfAlphabets.Add(23, "W");
            listOfAlphabets.Add(24, "X");
            listOfAlphabets.Add(25, "Y");
            listOfAlphabets.Add(26, "Z");
        }

    }
}

主程序类

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

namespace NumberToWords
{
    internal class Program
    {
        static void Main(string[] args)
        {
            int input = 1;
            Console.WriteLine("Please Add Number Of Set: ");
            input = Convert.ToInt32(Console.ReadLine());

            GenerateList(input);
        }
        public static void CheckFile()
        {
            string fileName = Environment.CurrentDirectory + "\\Result\\result.csv";
            try
            {
                if (File.Exists(fileName))
                {
                    File.Delete(fileName);
                }
                File.Create(fileName); 
            }
            catch (Exception Ex)
            {
            }
        }
        static void GenerateList(int number)
        {
            var list = new List<int>();
            for (int i = 0; i < number; i++)
            {
                list.Add(i);
            }
            GetCombination(list);
        }
        static void GetCombination(List<int> list)
        {
            var data = new Data();
            var listOfAlphabets = data.listOfAlphabets;
            var csv = new StringBuilder();
            CheckFile();
            string output = "";
            double count = Math.Pow(2, list.Count);
            for (int i = 1; i <= count - 1; i++)
            {
                string str = Convert.ToString(i, 2).PadLeft(list.Count, '0');
                for (int j = 0; j < str.Length; j++)
                {
                    if (str[j] == '1')
                    {
                        try
                        {
                            int xd = Convert.ToInt32(str[j]);
                                    output += listOfAlphabets.Where(x => x.Key == xd).Select(x => x.Value).FirstOrDefault();
                                    csv.AppendLine(output);
                        }
                        catch (Exception)
                        {

                            throw;
                        }
                    }
                }
                Console.WriteLine();
            }

            File.WriteAllText(Environment.CurrentDirectory + "\\Result\\result.csv", csv.ToString());

        }
    }
}

问题分析

现有代码完全偏离需求逻辑:

  • GenerateList生成0到输入值的数字列表,和目标数字无关
  • GetCombination用二进制位选择元素,未处理数字拆分逻辑(如将"512"拆为5+1+2或5+12)
  • 错误将二进制位的'1'转为数字1匹配字母,不符合映射规则

修正后的解决方案

采用递归回溯处理数字拆分,逐个位置尝试拆1位或2位有效数字(1-26),生成所有可能的单词组合:

完整修正代码

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace NumberToWords
{
    public class AlphabetMapper
    {
        private static readonly Dictionary<int, char> _numberToAlphabet = new Dictionary<int, char>();

        static AlphabetMapper()
        {
            for (int i = 1; i <= 26; i++)
            {
                _numberToAlphabet.Add(i, (char)('A' + i - 1));
            }
        }

        public static bool TryGetChar(int number, out char c)
        {
            return _numberToAlphabet.TryGetValue(number, out c);
        }
    }

    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("请输入目标数字:");
            string input = Console.ReadLine().Trim();

            if (!IsValidInput(input))
            {
                Console.WriteLine("输入无效,请输入纯数字且不以0开头(单个0除外,但0无对应字母)");
                return;
            }

            List<string> results = new List<string>();
            GenerateWords(input, 0, "", results);

            Console.WriteLine("\n所有可能的单词:");
            foreach (var word in results)
            {
                Console.WriteLine(word);
            }

            SaveResultsToCsv(results);
            Console.WriteLine("\n结果已保存到Result\\result.csv");
        }

        private static bool IsValidInput(string input)
        {
            if (string.IsNullOrEmpty(input))
                return false;

            if (input.StartsWith("0") && input.Length > 1)
                return false;

            return input.All(char.IsDigit);
        }

        private static void GenerateWords(string numberStr, int currentIndex, string currentWord, List<string> results)
        {
            if (currentIndex == numberStr.Length)
            {
                results.Add(currentWord);
                return;
            }

            // 尝试取1位数字
            string singleDigitStr = numberStr.Substring(currentIndex, 1);
            int singleDigit = int.Parse(singleDigitStr);
            if (AlphabetMapper.TryGetChar(singleDigit, out char singleChar))
            {
                GenerateWords(numberStr, currentIndex + 1, currentWord + singleChar, results);
            }

            // 尝试取2位数字
            if (currentIndex + 1 < numberStr.Length)
            {
                string doubleDigitStr = numberStr.Substring(currentIndex, 2);
                int doubleDigit = int.Parse(doubleDigitStr);
                if (doubleDigitStr[0] != '0' && AlphabetMapper.TryGetChar(doubleDigit, out char doubleChar))
                {
                    GenerateWords(numberStr, currentIndex + 2, currentWord + doubleChar, results);
                }
            }
        }

        private static void SaveResultsToCsv(List<string> results)
        {
            string directoryPath = Path.Combine(Environment.CurrentDirectory, "Result");
            Directory.CreateDirectory(directoryPath);
            string filePath = Path.Combine(directoryPath, "result.csv");

            using (StreamWriter writer = new StreamWriter(filePath))
            {
                foreach (var word in results)
                {
                    writer.WriteLine(word);
                }
            }
        }
    }
}

代码说明

  1. AlphabetMapper类:静态初始化数字到字母的映射,提供安全获取字母的方法,避免重复创建对象
  2. 输入验证:确保输入为纯数字、无前置0(单个0除外)
  3. 递归回溯逻辑:
    • 每次处理当前位置,先尝试取1位有效数字,递归处理剩余部分
    • 若剩余长度足够,尝试取2位有效数字(排除以0开头的情况),递归处理剩余部分
    • 处理完所有数字时,将当前单词加入结果列表
  4. 结果保存:自动创建目录并将结果写入CSV文件

测试示例

输入512,输出:

EAB
EL

输入4157,输出:

DAEG
DOG

内容的提问来源于stack exchange,提问作者Mr Blacky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 01:05:20