[leetcode]6. ZigZag Conversion字符串Z形排列
Posted 程序媛詹妮弗
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode]6. ZigZag Conversion字符串Z形排列相关的知识,希望对你有一定的参考价值。
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: new StringBuilder[]. For each row, allocate a new StringBuilder to save characters in such row.
Pay attention! StringBuilder is treated like variable-length arrays. So StringBuilder[] is like array of array
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形排列的主要内容,如果未能解决你的问题,请参考以下文章
6. 锯齿形变换 [leetcode 6: ZigZag Conversion]
6. 锯齿形变换 [leetcode 6: ZigZag Conversion]
学习(Swift)Leetcode 6. ZigZag Conversion