MCPcopy Create free account
hub / github.com/Blankj/awesome-java-leetcode / Solution

Class Solution

src/com/blankj/medium/_0006/Solution.java:11–63  ·  view source on GitHub ↗

author: Blankj blog : http://blankj.com time : 2017/12/11 desc :

Source from the content-addressed store, hash-verified

9 * </pre>
10 */
11class Solution {
12
13// public String convert(String s, int numRows) {
14// if (numRows <= 1) return s;
15// int len = s.length();
16// char[] chars = s.toCharArray();
17// int cycle = 2 * (numRows - 1);
18// StringBuilder sb = new StringBuilder();
19// for (int j = 0; j < len; j += cycle) {
20// sb.append(chars[j]);
21// }
22// for (int i = 1; i < numRows - 1; i++) {
23// int step = 2 * i;
24// for (int j = i; j < len; j += step) {
25// sb.append(chars[j]);
26// step = cycle - step;
27// }
28// }
29// for (int j = numRows - 1; j < len; j += cycle) {
30// sb.append(chars[j]);
31// }
32// return sb.toString();
33// }
34
35 public String convert(String s, int numRows) {
36 if (numRows <= 1) return s;
37 int len = s.length();
38 char[] chars = s.toCharArray();
39 StringBuilder[] sbs = new StringBuilder[numRows];
40 for (int i = 0; i < numRows; i++) {
41 sbs[i] = new StringBuilder();
42 }
43 int i = 0;
44 while (i < len) {
45 for (int j = 0; j < numRows && i < len; ++j) {
46 sbs[j].append(chars[i++]);
47 }
48 for (int j = numRows - 2; j >= 1 && i < len; --j) {
49 sbs[j].append(chars[i++]);
50 }
51 }
52 for (i = 1; i < numRows; i++) {
53 sbs[0].append(sbs[i]);
54 }
55 return sbs[0].toString();
56 }
57
58 public static void main(String[] args) {
59 Solution solution = new Solution();
60 System.out.println(solution.convert("PAYPALISHIRING", 3));// PAHNAPLSIIGYIR
61 System.out.println(solution.convert("ABCD", 4));
62 }
63}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected