ZigZag Conversion
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ZigZag Conversion相关的知识,希望对你有一定的参考价值。
1 public class Solution { 2 public String convert(String s, int numRows) { 3 // illegal parameters 4 if(s == null || s.length() == 0 || numRows <= 0) { 5 return s; 6 } 7 8 if(s.length() <= numRows || numRows == 1) { 9 return s; 10 } 11 12 13 // get column numbers of array 14 int numCols = 0; 15 int len = s.length(); 16 while(len > 0) { 17 len -= numRows * 2 - 2; 18 numCols += numRows - 1; 19 } 20 21 StringBuilder res = new StringBuilder(); 22 Character[][] array = new Character[numRows][numCols]; 23 boolean isDown = true; 24 int rowIndex = 0; 25 int colIndex = 0; 26 27 for(int i = 0; i < s.length(); i++) { 28 Character c = s.charAt(i); 29 array[rowIndex][colIndex] = c; 30 if(isDown) { 31 // going down direction 32 rowIndex++; 33 if(rowIndex == numRows) { 34 // time to change to lean direction 35 isDown = false; 36 rowIndex -= 2; 37 colIndex++; 38 } 39 } else { 40 // going lean direction 41 if(rowIndex == 0) { 42 // time to change to down direction 43 isDown = true; 44 rowIndex++; 45 } else { 46 rowIndex--; 47 colIndex++; 48 } 49 } 50 } 51 52 for(int i = 0; i < numRows; i++) { 53 for(int j = 0; j < numCols; j++) { 54 Character c = array[i][j]; 55 if(c == null) { 56 continue; 57 } else { 58 res.append(c); 59 } 60 } 61 } 62 63 return res.toString(); 64 } 65 }
以上是关于ZigZag Conversion的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode - 6 - ZigZag Conversion