我写了一个函数,我需要知道它的大O符号。 我试图解决这个问题,我得到O(N^2),但是我被告知这不是正确的答案。该功能的大O符号是什么?
有人可以告诉我什么是正确的符号,也是一步一步解释他们是如何来到这个答案?
该功能如下。
预先感谢
public static string Palindrome(string input)
{
string current = string.Empty;
string longest = string.Empty;
int left;
int center;
int right;
if (input == null || input == string.Empty || input.Length == 1) { return input; }
for (center = 1; center < input.Length -1; center++)
{
left = center - 1;
right = center + 1;
if (input[left] == input[center])
{
left--;
}
while (0 <= left && right < input.Length)
{
if (input[left] != input[right])
{
break;
}
current = input.Substring(left, (right - left + 1));
longest = current.Length > longest.Length ? current : longest;
left--;
right++;
}
}
return longest;
}
第一个'for'循环给你'N'迭代。 'while'循环循环'N/2'次最差情况和'1'最好情况。 – Blender
@Blender,while循环需要O(n^2)而不是O(n),请参阅我的答案以获取详细信息。 –
这功课吗? xD – evotopid