【发布时间】:2011-08-22 21:00:04
【问题描述】:
有人知道一种算法来对尾递归进行简单的递归吗? 更具体地说,您将如何将该算法应用于以下代码?
namespace Testing
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(match("?**", "aaa"));
Console.WriteLine(match("*#*?", "aa1$a1a1"));
Console.WriteLine(match("*#*", "aa11"));
Console.WriteLine(match("??*", "0110"));
Console.WriteLine(match("", "abc"));
Console.WriteLine(match("???", ""));
Console.ReadLine();
}
public static bool match(string p, string s)
{
if (p.Length == 0)
return true;
if (p.Length > s.Length)
return false;
bool firstLetterMatches = false;
char nextCharInStr = s[0];
switch (p[0])
{
case '*':
firstLetterMatches = 'a'<= nextCharInStr && nextCharInStr <= 'z';
break;
case '#':
firstLetterMatches = '0'<= nextCharInStr && nextCharInStr <= '9';
break;
case '?':
firstLetterMatches = ('a'<= nextCharInStr && nextCharInStr <= 'z') ||
('0'<= nextCharInStr && nextCharInStr <= '9');
break;
default:
return false;
}
return match(p,s.Substring(1)) ||
(firstLetterMatches && match(p.Substring(1),s.Substring(1)));
}
}
}
谢谢!
【问题讨论】:
-
由于 MS C# 编译器不发出尾调用,并且即使它发出 CLI 也不是强制 为了尊重它们,如果您想避免使用堆栈,您将寻找一种更手动的方法。我敢提
goto吗? -
@Marc - 我认为手动堆栈可能是更好的选择。他们要避免的另一件事是重复复制字符串。
-
@ChaosPandion 哦,当然你会使用你递增的
charIndex变量。当数据量不可预测时,手动堆栈很有用 - 不确定您是否需要。 -
我不明白为什么你们认为这个人想要一个 C# 特定的答案(关于性能)只是因为他用 C# 写了这个问题——我假设他只是在使用以C#为例,询问将函数重组为尾递归的一般问题。
-
@mquander 用 C# 中的示例标记了 C#?我认为我们可以假设 C#...
标签: c# tail-recursion