標籤:字串 數組 java 面試 演算法
【006-ZigZag Conversion(Z字型轉換)】
【LeetCode-面試演算法經典-Java實現】【所有題目目錄索引】
原題
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
APLSIIG
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 text, int nRows);
convert(“PAYPALISHIRING”,3) should return “PAHNAPLSIIGYIR”.
題目大意
輸入一個字串和指定的行數,將字元以Z字型輸出。
解題思路
計算出字元的最大列數,根據列數和行數建立一個一維數組,再計算每個字元中一維數組中的位置,再對一維數組中的字元進行緊湊操作,返回結果。
代碼實現
public class Solution { public String convert(String s, int nRows) { if (s == null || s.length() <= nRows || nRows == 1) { return s; } int index = s.length(); int rowLength = 0; // 計算行的長度,包括最後換行字元 int slash = nRows - 2; // 一個斜線除去首尾所佔用的行數 while (index > 0) { // 豎形的一列 index -= nRows; rowLength++; // 斜著的列數 for (int i = 0; i < slash && index > 0; i++) { rowLength++; index--; } } char[] result = new char[nRows * rowLength]; // 儲存結果的數組,最後一列用於儲存分行符號 for (int i = 0; i < result.length; i++) { // 初始化為空白格 result[i] = ‘ ‘; } int curColumn = 0; // 當前處理的行數 index = 0; while (index < s.length()) { // 處理豎線 for (int i = 0; i < nRows && index < s.length(); i++) { result[rowLength * i + curColumn] = s.charAt(index); index++; } curColumn++; // 處理斜線 for (int i = nRows - 2; i > 0 && index < s.length(); i--) { result[rowLength * i + curColumn] = s.charAt(index); curColumn++; index++; } }// System.out.println(new String(result)); // 對字元數組進行緊湊操作 index = 0; while (index < s.length() && result[index] != ‘ ‘) { // 找第一個是空格的字元位置 index++; } int next = index + 1; while (index < s.length()) { while (next < result.length && result[next] == ‘ ‘) { // 找不是空格的元素 next++; } result[index] = result[next]; index++; next++; } System.out.println(s); System.out.println(new String(result, 0, index)); return new String(result, 0, index); }}
評測結果
點擊圖片,滑鼠不釋放,拖動一段位置,釋放後在新的視窗中查看完整圖片。
特別說明
歡迎轉載,轉載請註明出處【http://blog.csdn.net/derrantcm/article/details/46938327】
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
【LeetCode-面試演算法經典-Java實現】【006-ZigZag Conversion(Z字型轉換)】