在 Swift 2 中,给定一个字符串 s
,这些语句的运行时复杂度是多少:
s.characters.count
s.endIndex
s.utf8.count
s.utf16.count
s.unicodeScalars.count
另外,如果我知道一个字符串仅包含字母,那么获取第 n 个字符的最有效方法是什么?
最佳答案
好吧,我正在尝试回答我自己的问题。如果我错了,请随时纠正我。
s.characters.count // O(N)
s.endIndex // O(1)
s.utf8.count // O(N)
s.utf16.count // O(N)
s.unicodeScalars.count // O(N)
苹果的documentation on CollectionType.count
表示“复杂度:如果 Index
符合 RandomAccessIndexType
,则为 O(1);否则为 O(N)。”由于 CharacterView
、UnicodeScalarView
、UTF16View
或 UTF8View
的 Index
都不符合RandomAccessIndexType
,访问它们的次数都是 O(N)。
关于swift - 获取不同表示形式的字符串长度的运行时复杂性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33094432/