LeetCode之6. Z 字形變換
阿新 • • 發佈:2018-11-23
LeetCode之6. Z 字形變換
- 將一個給定字串根據給定的行數,以從上往下、從左到右進行 Z 字形排列。
比如輸入字串為 “LEETCODEISHIRING” 行數為 3 時,排列如下:
之後,你的輸出需要從左往右逐行讀取,產生出一個新的字串,比如:“LCIRETOESIIGEDHN”。
請你實現這個將字串進行指定行數變換的函式:
string convert(string s, int numRows);
程式碼如下:
class Solution { public: string convert(string s, int numRows) { char **buf= new char*[numRows]; int length = s.length(); int numCols = getCols(length,numRows); for (int i = 0; i < numRows; i++) { buf[i] = new char[numCols]; } for (int i = 0; i < numRows; i++) { for (int j = 0; j < numCols; j++) { buf[i][j] = '\0'; } } //////////////////////////////////////////////////////////////// int count = 0; int t = numRows - 1>0?numRows-1:1; for (int m = 0; m < numCols; m++) { //偶數 if (m%t==0) { for (int n = 0; n < numRows; n++)//就是rows沒錯 { if (count>length) { break; } buf[n][m] = s[count++]; } } else//奇數 { for (int j = numRows - 2, k = m; j>0 && count<length; k++, j--) { buf[j][k] = s[count++]; } m += t-1; m--; } } string ret; for (int i = 0; i < numRows; i++) { for (int j = 0; j < numCols;j++) { if (buf[i][j]!='\0') { ret.append(1, buf[i][j]); } } } return ret; } int getCols(int s,int n){ int i = 0; int t = n - 1>0?n-1:1; int ts = 0; for (i = 0; ts < s;i++) { if (i%t==0) { ts += n; } else { ts++; } } return i; } };