本文介绍了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参数必须大于或等于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)吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 13:30