简体   繁体   English

字符串切片的时间复杂度是多少? O(k) 或 O(n)

[英]What is the time complexity of string slice? O(k) or O(n)

Is the time complexity of python str slice O(k) or O(n)? python str slice 的时间复杂度是 O(k) 还是 O(n)?

The answers I am reading suggest its O(k) but I don't understand how.我正在阅读的答案表明它的 O(k) 但我不明白如何。

For example例如

my_str = "thisismystringfortesting"

sub_str = my_str[3:10]

I understand its extracting only (k) characters, but doesn't the operation have to convert the whole string into a list first before the slice?我了解它仅提取(k)个字符,但该操作是否必须在切片之前先将整个字符串转换为列表? My thought process is that the conversion of the entire string into a list alone would cost O(n).我的想法是,将整个字符串单独转换为列表将花费 O(n)。 Unless only part of the string gets converted into a list?除非只有部分字符串被转换成列表?

So can someone please explain is string slicing on Python O(k) or O(n)?那么有人可以解释一下 Python O(k) 或 O(n) 上的字符串切片吗?

Thanks so much!非常感谢!

The relevant code is here and it is O(k) as it can be seen line 1628相关代码在这里,它是 O(k),可以看到第 1628 行

result_buf = PyBytes_AS_STRING(result);
for (cur = start, i = 0; i < slicelength;cur += step, i++) {
        result_buf[i] = source_buf[cur];
}
return result;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM