1. 程式人生 > >【LeetCode-面試演算法經典-Java實現】【006-ZigZag Conversion(Z字型轉換)】

【LeetCode-面試演算法經典-Java實現】【006-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
  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); } }

評測結果

  點選圖片,滑鼠不釋放,拖動一段位置,釋放後在新的視窗中檢視完整圖片。

這裡寫圖片描述

特別說明