【问题标题】:Time-complexity of looking at item in stringbuider - C#在 stringbuilder 中查看项目的时间复杂度 - C#
【发布时间】:2018-07-04 13:46:43
【问题描述】:

我在StringBuilder 中保存了一些长文本,我想要一些特定的项目

StringBuilder builder = new StringBuilder();
//fill builder
int i = someNumber();
char ch = builder[i];

最后一条指令的时间复杂度是多少 (char ch = builder[i])?是不是恒定的

O(1)

还是线性的?

O(i)

【问题讨论】:

    标签: c# time-complexity stringbuilder


    【解决方案1】:

    这是一个常数,因为您要给出获取元素的确切位置。所以在这种情况下 O(1)。更多细节在这里 What is the complexity of this simple piece of code?

    【讨论】:

      【解决方案2】:

      char ch = builder[i] 是 O(1)。

      因为 StringBuilder 使用了数组索引。

      【讨论】:

        【解决方案3】:

        根据Reference SourceStringBuilder 类将字符串存储在 char 数组中。

        通过属性 getter this[int index] 访问此数组会进行一些检查,然后返回数组项:

            internal char[] m_ChunkChars;                // The characters in this block
            //...more stuff
        
            [System.Runtime.CompilerServices.IndexerName("Chars")]
            public char this[int index] {
                // 
        
                get {
                    StringBuilder chunk = this;
                    for (; ; )
                    {
                        int indexInBlock = index - chunk.m_ChunkOffset;
                        if (indexInBlock >= 0)
                        {
                            if (indexInBlock >= chunk.m_ChunkLength)
                                throw new IndexOutOfRangeException();
                            return chunk.m_ChunkChars[indexInBlock];
                        }
                        chunk = chunk.m_ChunkPrevious;
                        if (chunk == null)
                            throw new IndexOutOfRangeException();
                    }
                }
                //... more stuff
            }
        

        因此复杂度是 O(1) 或恒定访问时间。

        【讨论】:

          【解决方案4】:

          查看StringBuilder的实现,它是O(1),因为是使用char[]

              //
              //
              //  CLASS VARIABLES
              //
              //
              internal char[] m_ChunkChars;                // The characters in this block
              internal StringBuilder m_ChunkPrevious;      // Link to the block logically before this block
              internal int m_ChunkLength;                  // The index in m_ChunkChars that represent the end of the block
              internal int m_ChunkOffset;                  // The logial offset (sum of all characters in previous blocks)
              internal int m_MaxCapacity = 0;
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-02-08
            • 1970-01-01
            • 1970-01-01
            • 2022-06-10
            • 2011-11-22
            • 2018-02-21
            相关资源
            最近更新 更多