6.ZigZag Conversion

题目链接

题目大意:将一个给定字符串转换成z字型,如下所示,给出z字型的行数,然后排成z字型,再按行输出结果。

法一(借鉴):代码如下(耗时59ms):

 1     public String convert(String s, int numRows) {
 2         if(numRows <= 1) {
 3             return s;
 4         }
 5         StringBuilder res = new StringBuilder();
 6         int len = 2 * numRows - 2;
 7         for(int i = 0; i < numRows; i++) {
 8             //填充每一行的数据
 9             for(int j = i; j < s.length(); j += len) {
10                 //填充非斜位置的规律数值
11                 res.append(s.charAt(j));
12                 //处理非首行和非尾行的数据
13                 if(i != 0 && i != numRows - 1) {
14                     int tmp = j + len - 2 * i;
15                     if(tmp < s.length()) {
16                         res.append(s.charAt(tmp));
17                     }
18                 }
19             }
20         }
21         return res.toString();
22     }
View Code

猜你喜欢

转载自www.cnblogs.com/cing/p/9006943.html
今日推荐