No.006:ZigZag Conversion,no.006zigzag
題目:
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 NA P L S I I GY I R
Write the code that will take a string and make this conversion given a number of rows:
string convert(string text, int nRows);
官方難度:
Easy
翻譯:
字串"PAYPALISHIRING",被拆成幾列寫成如下ZigZag模式,寫出轉譯的代碼。
例子:
以上的例子如果表達的不夠清楚,再給一個清晰的例子:
a g m s y
b f h l n r t x z
c e i k o q u w
d j p v
返回"agmsybfhlnrtxzceikoquwdjpv"
思路:
1.用兩次遍曆,把新字串加進數組。
2.頭尾兩行需要特殊處理,間隔是個定值=2*(nRows-1)。
3.根據走勢是從下往上還是從下往上,間隔是不同的,使用一個int型的標誌位,每次改變之後乘以-1來控制。
解題中可能遇到的困難:
1.內迴圈的index是i+j,允出準則是i+j<array.length。
解題代碼:
1 private static String method(String text, int nRows) { 2 char[] array = text.toCharArray(); 3 StringBuffer sb = new StringBuffer(); 4 // 從上至下/從下至上的標誌位 5 int flag = 1; 6 // 按行遍曆 7 for (int i = 0; i < nRows; i++) { 8 // 每一行的資料 9 for (int j = 0; i + j < array.length;) {10 sb.append(array[i + j]);11 // 極點有特殊的處理方式12 if (i == 0 || i == nRows - 1) {13 j += 2 * (nRows - 1);14 } else {15 if (flag == 1) {16 // 從上至下處理17 j += 2 * (nRows - i - 1);18 } else {19 // 從下至上處理20 j += 2 * i;21 }22 // 下次改變方向23 flag *= -1;24 }25 }26 // 結束一行遍曆,方向標誌位還原27 flag = 1;28 }29 return sb.toString();30 }View Code
測試代碼地址:
https://github.com/Gerrard-Feng/LeetCode/blob/master/LeetCode/src/com/gerrard/algorithm/easy/Q006.java
LeetCode題目地址:
https://leetcode.com/problems/zigzag-conversion/
PS:如有不正確或提高效率的方法,歡迎留言,謝謝!