【问题标题】:Time complexity of StringBuilder length() methodStringBuilder length() 方法的时间复杂度
【发布时间】:2020-06-19 17:31:20
【问题描述】:

StringBuilder 类的 length() 方法的时间复杂度是多少?

String str = "hello";
StringBuilder sb = new StringBuilder(str);

System.out.println(sb.length()); // should print 5

我的假设是 O(n),其中 n 是字符串中的字符数,类似于 String 类中的 length()。

【问题讨论】:

  • O(1)。长度存储在一个实例字段中,并通过一个简单的操作简单地返回。
  • 重要的是,String 也是 O(1)。

标签: java string stringbuilder


【解决方案1】:

这是StringBuilder类中的成员变量:

/**
 * The count is the number of characters used.
 */
int count;

这是length()的代码:

/**
 * Returns the length (character count).
 *
 * @return  the length of the sequence of characters currently
 *          represented by this object
 */
@Override
public int length() {
    return count;
}

你怎么看?

【讨论】:

    猜你喜欢
    • 2018-07-04
    • 2012-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-14
    • 1970-01-01
    • 2018-09-14
    相关资源
    最近更新 更多