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」.java
輸入一個字符串和指定的行數,將字符以Z字型輸出。數組
計算出字符的最大列數,根據列數和行數建立一個一維數組,再計算每一個字符中一維數組中的位置,再對一維數組中的字符進行緊湊操做,返回結果。app
【解析】ui
第一次看到這個題目的人,可能不知道ZigZag是什麼意思,簡單解釋一下,就是把字符串原順序012345……按下圖所示排列:this
比較直觀的解法是,用一個字符串數組 string[rows] 來存儲每一行,最後一拼接就是最終結果。spa
用一個delta表示正向仍是反向,即上圖中從第一行到最後一行仍是最後一行到第一行。.net
代碼以下所示:code
[java] view plain copyblog
【網上解法】ip
如 http://blog.csdn.NET/cshaxu/article/details/12507201 說的最爲簡潔:
發現全部行的重複週期都是 2 * nRows - 2
對於首行和末行之間的行,還會額外重複一次,重複的這一次距離本週期起始字符的距離是 2 * nRows - 2 - 2 * i
代碼以下所示:
[java] view plain copy
【總結】
這道題屬於簡單題,找規律便可,循環週期可能比較容易找,週期中間的規律 2 * nRows - 2 - 2 * i 可能不大好找。
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); } }
這題的解法也很單一,也沒有很難的時間複雜度,大體都是O(n)。
咱們想一下思路,這個zigzag有一個性質不知道大家發現了沒有。
對於數列123456789來講當nRows=4的時候第一列確定是滿列,而後第二列的位置=2%4+1也就是3那麼第三列的位置就是3%4+1也就是2
這樣咱們一個循環就能夠完成這個操做了,這裏說的操做僅僅是能夠放在一個二維數組中了,那麼咱們可不能夠利用這個性質直接輸出呢?
首先讀取一個字符串從1開始若是=1或者%4+(4-2)+1=0的話則輸出,這樣一層一層的輸出就行了,可是這樣咱們須要不斷的遍歷操做,可是若是咱們操做數組下標這個時間複雜度增長的問題就解決了。
代碼以下:
[java] view plain copy
這個代碼的主要特色就是根據nRows作的時間複雜度,它的時間複雜度通過計算應該是O(n^2/2n-2)當n趨向於無限大的時候O趨向於O(n),針對String比較長而nRows比較短的狀況應該有奇效。