简体   繁体   English

Java StringBuilder.substring()方法的时间复杂度是多少? 如果它是线性的,是否有一个恒定的时间复杂度方法来获得子串?

[英]What is the time complexity of Java StringBuilder.substring() method? If it is linear, is there a constant time complexity method to get a substring?

In my opinion it should be constant(O(1)) time complexity. 在我看来,它应该是恒定的(O(1))时间复杂度。 However I was told that a new String object has to be instantiated when invoking stringBuilder.substring() method. 但是我被告知在调用stringBuilder.substring()方法时必须实例化一个新的String对象。 (It is not static method). (这不是静态方法)。 If this is true, how can I get a substring within a constant time complexity? 如果这是真的,我怎样才能在恒定的时间复杂度内获得子串?

You cannot possibly create a String from a StringBuilder in constant time and have its immutability maintained. 您不可能在常量时间内从StringBuilder创建String并保持其不变性。 Additionally, as of Java 7 Update 25, even String#substring() is linear time because structural sharing actually caused more trouble than it avoided: substring of a huge string retained a reference to the huge char array. 此外,从Java 7 Update 25开始,即使String#substring()也是线性时间,因为结构共享实际上比它避免的更麻烦:巨大字符串的子字符串保留了对巨大char数组的引用。

In my opinion it should be constant(O(1)) time complexity. 在我看来,它应该是恒定的(O(1))时间复杂度。

This is not possible. 这是不可能的。 Since Java strings are immutable, while StringBuilder s are mutable, all operations that produce a String must make a copy. 由于Java字符串是不可变的,而StringBuilder是可变的,因此生成String所有操作都必须复制。

If this is true, how can I get a substring within a constant time complexity? 如果这是真的,我怎样才能在恒定的时间复杂度内获得子串?

You cannot. 你不能。 Without a copy, changing characters inside a substring would mutate the String , which is not allowed. 如果没有副本,更改子字符串中的字符会改变String ,这是不允许的。

StringBuilder's substring actually copies the characters from start index to end index, so it tries to array copy of characters of substring length(ie end index-startindex). StringBuilder的子字符串实际上将字符从起始索引复制到结束索引,因此它尝试对子字符串长度的字符进行数组复制(即end index-startindex)。 This will be the time complexity of this operation O(substringlength) as the loop runs from start index to end index which cannot be avoided. 这将是此操作的时间复杂度O(substringlength),因为循环从起始索引到结束索引,这是无法避免的。 With this the substring char[], string object will be instantiated. 使用子字符串char [],将实例化字符串对象。

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

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