Java StringBuilder.setLength()-时间复杂度为O(1)吗? [英] Java StringBuilder.setLength() - is time complexity O(1)?

查看:182
本文介绍了Java StringBuilder.setLength()-时间复杂度为O(1)吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我打算对StringBuilders中的最后一个字符进行很多删除.对我来说,使用sb.setLength(sb.length() - 1);的解决方案看起来不错.但是,由于这些删除将处于循环中,因此我需要知道其复杂性.

I'm planning to perform lots of deletes of the last character in StringBuilders. The solution to use sb.setLength(sb.length() - 1); looks good to me. However, since these deletions will be in a loop, I need to know complexity of it.

据我所知,此操作只是减少StringBuilder对象的一些私有属性,并且不对字符本身执行任何复制/克隆/复制操作,因此它的时间为O(1),应该可以快速运行.

The way I understand it is that this operation simply decrements some private attribute of my StringBuilder object and does not perform any copying/cloning/duplicating of the characters themselves, thus it is O(1) in time and should work fast.

我说得对吗?

推荐答案

来自文档:

设置字符序列的长度.该序列将更改为新的字符序列,其长度由参数指定.对于每个小于newLength的非负索引k,如果k小于旧字符序列的长度,则新字符序列中索引k处的字符与旧序列中索引k处的字符相同;否则,它是空字符'\ u0000'.换句话说,如果newLength参数小于当前长度,则将长度更改为指定的长度. 如果newLength自变量大于或等于当前长度,则将附加足够的空字符('\ u0000'),以便长度成为newLength自变量.

Sets the length of the character sequence. The sequence is changed to a new character sequence whose length is specified by the argument. For every nonnegative index k less than newLength, the character at index k in the new character sequence is the same as the character at index k in the old sequence if k is less than the length of the old character sequence; otherwise, it is the null character '\u0000'. In other words, if the newLength argument is less than the current length, the length is changed to the specified length. If the newLength argument is greater than or equal to the current length, sufficient null characters ('\u0000') are appended so that length becomes the newLength argument.

newLength参数必须大于或等于0.

The newLength argument must be greater than or equal to 0.

我会说是的.但是从时间复杂度的角度来看,我不会看到它.我们在循环中使用StringBuilder而不是String的原因是因为String是不可变的.因此,当我们尝试更改它时,将始终创建一个新的字符串对象.更改StringBuilder对象的长度时,不会创建新对象.

I would say yes. But I wouldn't see it from the point of view of time complexity. The reason we use StringBuilder instead of String in a loop is because Strings are immutable. Hence a new string object will always be created when we try to change it. When you change the length of a StringBuilder object, no new object is created.

这篇关于Java StringBuilder.setLength()-时间复杂度为O(1)吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆