码迷,mamicode.com
首页 > 其他好文 > 详细

理解StringBuilder

时间:2019-04-20 09:22:58      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:http   pen   code   图片   nta   return   ide   sam   The   

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 }

 

理解StringBuilder

标签:http   pen   code   图片   nta   return   ide   sam   The   

原文地址:https://www.cnblogs.com/liuliu5151/p/10739790.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!