題目:
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 A P L S I I G Y 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。
解題代碼:
測試代碼地址:
https://github.com/Gerrard-Feng/LeetCode/blob/master/LeetCode/src/com/gerrard/algorithm/easy/Q006.java
LeetCode題目地址:
https://leetcode.com/problems/zigzag-conversion/
PS:如有不正確或提高效率的方法,歡迎留言,謝謝!