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

[leetcode]6. ZigZag Conversion字符串Z形排列

时间:2019-04-04 10:01:03      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:his   inpu   --   class   exp   alt   dde   array   div   

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)

P   A   H   N
A P L S I I G
Y   I   R

And then read line by line: "PAHNAPLSIIGYIR"

Write the code that will take a string and make this conversion given a number of rows:

string convert(string s, int numRows);

Example 1:

Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"


Example 2:

Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"

Explanation: P I N A L S I G Y A H R P I

 

Solution1: 

Step1: for each row, allocate a new StringBuilder to sort characters in such row

技术图片

Step2: we can observe that for 1st and last row,  chars will be added into sb[0] and sb[numRows-1], seperately.

                                       for sloping slide,  chars will be added in sb[numRows -2 ] ... sb[1]

技术图片

Step3: convert each row‘s StringBuilder into result String

技术图片

 

code:

 1 /*
 2 Time Complexity: O(n)
 3 Space Complexity: O(n)
 4 */
 5 
 6 class Solution {
 7    public String convert(String s, int numRows) {
 8         char[] c = s.toCharArray();
 9         int len = c.length;
10         StringBuilder[] sb = new StringBuilder[numRows];
11         // 要按row来进行遍历,每一个row先allocate一个StringBuilder
12         for (int i = 0; i < sb.length; i++) {
13             sb[i] = new StringBuilder();
14         }
15 
16         int idx = 0; //用来扫String s
17         while (idx < len) {
18             for (int i = 0; i < numRows && idx < len; i++) {
19                 sb[i].append(c[idx++]);
20             }
21             // sloping side
22             for (int i = numRows - 2; i >= 1 && idx < len; i--) {
23                 sb[i].append(c[idx++]);
24             }
25 
26         }
27         //从sb[0]开始,将sb[1], sb[2], sb[3]... append到一个StringBuilder
28         for (int i = 1; i < sb.length; i++) {
29             sb[0].append(sb[i]);
30         }
31         return sb[0].toString();
32     }
33 }

 

[leetcode]6. ZigZag Conversion字符串Z形排列

标签:his   inpu   --   class   exp   alt   dde   array   div   

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

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