【问题标题】: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
【解决方案2】:
char ch = builder[i] 是 O(1)。
因为 StringBuilder 使用了数组索引。
【解决方案3】:
根据Reference Source,StringBuilder 类将字符串存储在 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;