zoukankan      html  css  js  c++  java
  • 理解StringBuilder

    StringBuilder objects are like String objects, except that they can be modified. Internally, these objects are treated like variable-length arrays that contain a sequence of characters. At any point, the length and content of the sequence can be changed through method invocations.

    Strings should always be used unless string builders offer an advantage in terms of simpler code (see the sample program at the end of this section) or better performance. For example, if you need to concatenate a large number of strings, appending to a StringBuilder object is more efficient.

    [leetcode]6. ZigZag Conversion字符串Z形排列 中,我们对每一个row,都要新建一个StringBuilder来存该row的info

    代码写出来如下,发现StringBuilder 被当做array来使用,所以StringBuilder[]相当于array of array 

     1 class Solution {
     2    public String convert(String s, int numRows) {
     3         char[] c = s.toCharArray();
     4         int len = c.length;
     5         StringBuilder[] sb = new StringBuilder[numRows];
     6         // 要按row来进行遍历,每一个row先allocate一个StringBuilder
     7         for (int i = 0; i < sb.length; i++) {
     8             sb[i] = new StringBuilder();
     9         }
    10 
    11         int idx = 0; //用来扫String s
    12         while (idx < len) {
    13             for (int i = 0; i < numRows && idx < len; i++) {
    14                 sb[i].append(c[idx++]);
    15             }
    16             // sloping side
    17             for (int i = numRows - 2; i >= 1 && idx < len; i--) {
    18                 sb[i].append(c[idx++]);
    19             }
    20 
    21         }
    22         //从sb[0]开始,将sb[1], sb[2], sb[3]... append到一个StringBuilder
    23         for (int i = 1; i < sb.length; i++) {
    24             sb[0].append(sb[i]);
    25         }
    26         return sb[0].toString();
    27     }
    28 }
  • 相关阅读:
    大数据组件
    k8s 证书过期时间调整
    k8s Metrics Server 获取资源指标与 hpa 部署
    k8s修改集群coredns
    k8s 版本升级
    k8s node节点剔除与增加
    etcd 单节点部署、备份与恢复
    k8s 连接ceph集群
    efk收集k8s 容器日志安装记录
    prometheus 监控k8s 安装测试记录
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/10739790.html
Copyright © 2011-2022 走看看