果果1020

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

 1 public class Solution {
 2     public String convert(String s, int numRows) {
 3         if (s == null || numRows < 2 || s.length() <= numRows) {
 4             return s;
 5         }
 6         StringBuilder sb = new StringBuilder(s.length());
 7         int gap = 2 * numRows - 2;
 8         for (int i = 0; i < numRows; i++) {
 9             for (int j = i; j < s.length(); j += gap) {
10                 sb.append(s.charAt(j));
11                 if (i > 0 && i < numRows - 1) {
12                     int t = j + gap - 2 * i;
13                     if (t < s.length()) {
14                         sb.append(s.charAt(t));
15                     }
16                 }
17             }
18         }
19         return sb.toString();
20     }
21 }

 

posted on 2017-01-02 12:27  果果1020  阅读(112)  评论(0)    收藏  举报