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」.java

題目大意

  輸入一個字符串和指定的行數,將字符以Z字型輸出。數組

解題思路

  計算出字符的最大列數,根據列數和行數建立一個一維數組,再計算每一個字符中一維數組中的位置,再對一維數組中的字符進行緊湊操做,返回結果。app

【解析】ui

第一次看到這個題目的人,可能不知道ZigZag是什麼意思,簡單解釋一下,就是把字符串原順序012345……按下圖所示排列:this

比較直觀的解法是,用一個字符串數組 string[rows] 來存儲每一行,最後一拼接就是最終結果。spa

用一個delta表示正向仍是反向,即上圖中從第一行到最後一行仍是最後一行到第一行。.net

代碼以下所示:code

 

[java] view plain copyblog

在CODE上查看代碼片派生到個人代碼片

  1. public class Solution {  
  2.     public String convert(String s, int nRows) {  
  3.         int len = s.length();  
  4.         if (len == 0 || nRows <= 1) return s;  
  5.           
  6.         String[] ans = new String[nRows];  
  7.         Arrays.fill(ans, "");  
  8.         int row = 0, delta = 1;  
  9.         for (int i = 0; i < len; i++) {  
  10.             ans[row] += s.charAt(i);  
  11.             row += delta;  
  12.             if (row >= nRows) {  
  13.                 row = nRows-2;  
  14.                 delta = -1;  
  15.             }  
  16.             if (row < 0) {  
  17.                 row = 1;  
  18.                 delta = 1;  
  19.             }  
  20.         }  
  21.           
  22.         String ret = "";  
  23.         for (int i = 0; i < nRows; i++) {  
  24.             ret += ans[i];  
  25.         }  
  26.         return ret;  
  27.     }  
  28. }  


【網上解法】ip

 

如 http://blog.csdn.NET/cshaxu/article/details/12507201 說的最爲簡潔:

發現全部行的重複週期都是 2 * nRows - 2

對於首行和末行之間的行,還會額外重複一次,重複的這一次距離本週期起始字符的距離是 2 * nRows - 2 - 2 * i

代碼以下所示:

 

[java] view plain copy

在CODE上查看代碼片派生到個人代碼片

  1. public class Solution {  
  2.     public String convert(String s, int nRows) {  
  3.         int len = s.length();  
  4.         if (len == 0 || nRows < 2) return s;  
  5.           
  6.         String ret = "";  
  7.         int lag = 2*nRows - 2; //循環週期  
  8.         for (int i = 0; i < nRows; i++) {  
  9.             for (int j = i; j < len; j += lag) {  
  10.                 ret += s.charAt(j);  
  11.                   
  12.                 //非首行和末行時還要加一個  
  13.                 if (i > 0 && i < nRows-1) {  
  14.                     int t = j + lag - 2*i;  
  15.                     if (t < len) {  
  16.                         ret += s.charAt(t);  
  17.                     }  
  18.                 }  
  19.             }  
  20.         }  
  21.         return ret;  
  22.     }  
  23. }  


【總結】

 

這道題屬於簡單題,找規律便可,循環週期可能比較容易找,週期中間的規律 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

 

  1. public class ZigZagConversion {  
  2.     public static void main(String[] args){  
  3.         String text = "123456789";  
  4.         System.out.println(method(text, 4));  
  5.     }  
  6.     public static String method(String text ,int nRows){  
  7.         StringBuilder result = new StringBuilder();  
  8.         char[] string = text.toCharArray();  
  9.         for(int i =0;i<nRows;i++){  
  10.             for(int j = i;j<string.length;){  
  11.                 if(i==0||i==(nRows-1)){//處在第一行和最後一行,不用輸出中間數  
  12.                     result.append(string[j]);  
  13.                     j += nRows*2-2;  
  14.                 }else {//處在中間行,要多輸出中間數  
  15.                       
  16.                     if(j>nRows){  
  17.                         result.append(string[j-i*2]);  
  18.                     }  
  19.                     result.append(string[j]);  
  20.                     j += nRows*2-2;  
  21.                 }  
  22.             }  
  23.         }  
  24.         return result.toString();  
  25.     }  
  26. }  

這個代碼的主要特色就是根據nRows作的時間複雜度,它的時間複雜度通過計算應該是O(n^2/2n-2)當n趨向於無限大的時候O趨向於O(n),針對String比較長而nRows比較短的狀況應該有奇效。

相關文章
相關標籤/搜索