这道题比较简单,需要注意的是输入的时候,日期后面有个小点,不注意容易出错。
C++的switch-case不能应用在string上面,这点让人十分不爽,对输入中的月份名称的辨认,我是使用的有穷自动机识别的。现拟制作一个代码生成器,根据字符串序列生成这些字符串的识别自动机,返回这些字符串的enum,然后即可利用C++的switch-case进行处理。
题目描述
原题链接:POJ 1008 Maya Calendar
解题分析
这道题比较简单,需要注意的是输入的时候,日期后面有个小点,不注意容易出错。
C++的switch-case不能应用在string上面,这点让人十分不爽,对输入中的月份名称的辨认,我是使用的有穷自动机识别的。现拟制作一个代码生成器,根据字符串序列生成这些字符串的识别自动机,返回这些字符串的enum,然后即可利用C++的switch-case进行处理。
等有空的时候用lex和yacc好好弄一下的,现在先用C#写个不完全版的凑合一下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CPPStringSwitchCase
{
class Program
{
static void Trans(IEnumerable<string> KeyWords, int length)
{
var GroupedKeyWords = KeyWords.Where(key=>key.Length > length).GroupBy(key => key[length]);
if (GroupedKeyWords.Count() == 0) return;
string prefix = "";
for (int i = 0; i < length + 1; i++)
prefix += "\t";
Console.WriteLine(String.Concat(prefix, "switch(input[", length, "]) {"));
foreach (IGrouping<char, string> GroupedKeyWord in GroupedKeyWords)
{
Console.WriteLine(String.Concat(prefix, "case ", GroupedKeyWord.Key, ":"));
Trans(GroupedKeyWord, length + 1);
Console.WriteLine(String.Concat(prefix, "\tbreak;"));
}
Console.WriteLine(String.Concat(prefix, "default: return NOT_FOUND;"));
Console.WriteLine(String.Concat(prefix, "}"));
}
static void Main(string[] args)
{
string EnumName = "XX";
List<string> KeyWords = new List<string>();
while (true)
{
string tmp = Console.ReadLine();
if (string.IsNullOrEmpty(tmp))
break;
KeyWords.Add(tmp);
}
Console.WriteLine("enum {0}", EnumName);
Console.WriteLine("{");
foreach (string keyWord in KeyWords)
Console.WriteLine("\t{0},", keyWord);
Console.WriteLine("\t{0}", "NOT_FOUND");
Console.WriteLine("}");
Console.WriteLine(String.Concat(EnumName, " Map", EnumName, "(const char & input) {"));
Trans(KeyWords, 0);
Console.WriteLine("}");
}
}
}
总结
总结等以后用重做小工具后再补吧,最近好忙>_<