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 }
  • 相关阅读:
    python---自定义分页类
    python---正则中的(?P<name>group)
    学习windows编程 day6 之模拟记事本
    学习windows编程 day5 之按键消息
    some websit
    android/iphone/windows/linux声波通讯库
    无线点餐系统
    android实现弧形进度表盘效果
    与Sevice实现双向通信
    android code bbs for developer
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/10739790.html
Copyright © 2011-2022 走看看