LeetCode【6】. ZigZag Conversion,leetcodezigzag
ZigZag Conversion
一、題目如下: 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 NA P L S I I GY 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 text, int nRows);
convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".
題目大意為將給定字串按如上的“Z”字鋸齒形進行重排。
二、思路
,將該圖形進行分區。
圖一、分區圖
從以上我們可以很清晰地根據給定字串的索引來求出其在一個“Z”型中所處的位置,是處於豎行還是斜行,是在第幾排。思路清晰,結合圖及以下代碼、注釋,可以很快明白思路。
三、Java實現
public class Solution { public String convert(String s, int numRows) { int sl = s.length(); if(numRows<=1||sl<=numRows) return s; int N = (int)Math.ceil((double)sl/(2*numRows-2)); //1. 計算分區大小,最後一個區可能是充滿也可能是不滿,所以向上取整 int index1=0, index2=0; int nN = 2*numRows-2; //2. 求出一分區內有多少元素。豎行是numRows個,斜行需減去頭尾兩個元素 StringBuffer sb = new StringBuffer(); for(int iR = 1; iR<=numRows; iR++) //3. 按行進行掃描輸出 { for(int jN = 1; jN<=N; jN++) //4. 掃描iR行的不同分區 { //4.1. index1為第jN塊的第iR行豎值索引 index1 = (jN-1)*nN + iR; if(index1<=sl) { sb.append(s.charAt(index1-1)); } //4.2. index2為第jN塊的第iR行斜值索引,斜行去迴轉尾兩個 if((iR!=1)&&(iR!=numRows)) { index2 = (jN-1)*nN + 2*numRows -iR; if(index2<=sl) { sb.append(s.charAt(index2-1)); } } } } return sb.toString(); }}