Algorithm 这个函数的大O表示法是什么?

Algorithm 这个函数的大O表示法是什么?,algorithm,big-o,Algorithm,Big O,我已经写了一个函数,我需要知道它的大O符号。 我自己也尝试过解决这个问题,我得到了O(N^2),但是我被告知这不是正确的答案 有人能告诉我正确的表示法是什么,并一步一步地解释他们是如何得出这个答案的吗 函数如下所示 提前谢谢 public static string Palindrome(string input) { string current = string.Empty; string longest = string.Empty;

我已经写了一个函数,我需要知道它的大O符号。 我自己也尝试过解决这个问题,我得到了O(N^2),但是我被告知这不是正确的答案

有人能告诉我正确的表示法是什么,并一步一步地解释他们是如何得出这个答案的吗

函数如下所示

提前谢谢

    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;
    }
公共静态字符串回文(字符串输入)
{
string current=string.Empty;
字符串最长=string.Empty;
int左;
国际中心;
国际权利;
if(input==null | | input==string.Empty | | input.Length==1){return input;}
对于(中心=1;中心
本部分采用O(n^2):

//while循环的O(n)次

还有一个外部O(n),
用于
循环,它导致O(n*n^2)

您可以通过更改以下行来改进算法:

   current = input.Substring(left, (right - left + 1)); 
   longest = current.Length > longest.Length ? current : longest;
致:

最后返回一个从longestLeft到longestRight的子字符串。实际上,避免过多地使用
substring
方法。

if(input[left]!=input[right])
语句执行了O(n^2)次,下面的几个赋值也是如此,特别是:

current = input.Substring(left, (right - left + 1));
在子字符串函数的典型实现中,一系列字符从字符串复制到一个新的字符串对象。该复制是一个O(n)操作,导致循环和子字符串操作需要O(n^3)时间

可以通过将赋值移动到
当前
最长
while
构造的右括号后来解决此问题。但请注意,
左--;
右++;
将比现有代码执行多一倍,因此对
当前
的赋值将变为

current = input.Substring(left+1, (right-1 - (left+1) + 1));


因此,O(n)子串操作最多执行O(n)次。

for的第一个
循环给出
n
迭代。
while
循环
n/2
次最坏情况和
1
次最佳情况。@Blender,while循环使用O(n^2)而不是O(n),详情请参阅我的答案。非常感谢,我完全忽略了子字符串函数
   currentLength = right - left + 1;
   if(currentLength > longest)
   { 
     longest = current.Length > longest.Length ? current : longest;
     longestLeft = left;
     longestRight = right;
   }
current = input.Substring(left, (right - left + 1));
current = input.Substring(left+1, (right-1 - (left+1) + 1));
current = input.Substring(left+1, (right-left-1));