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 }
  • 相关阅读:
    POJ 1149
    最小费用最大流邻接表模板
    poj 1724 最短路+优先队列(两个约束条件)
    hdu 4786 最小生成树与最大生成树
    hdu 4081 最小生成树变形
    poj 3228 二分+最大流
    poj 2516 最小费用最大流
    hdu 3605 二分图多重匹配
    hdu 3605 最大流sap+二进制思想(啊啊)
    hdu 3572 最大流判断满流
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/10739790.html
Copyright © 2011-2022 走看看