No.006:ZigZag Conversion,no.006zigzag

來源:互聯網
上載者:User

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:如有不正確或提高效率的方法,歡迎留言,謝謝!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.