Problem:
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
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 s, int numRows);
Example 1:
Input: s = “PAYPALISHIRING”, numRows = 3
Output: “PAHNAPLSIIGYIR”
Example 2:
Input: s = “PAYPALISHIRING”, numRows = 4
Output: “PINALSIGYAHRPI”
Explanation:
P I N
A L S I G
Y A H R
P I
Intuition:
这个题目我的思路是这样的。我们只要最后能够返回一个String rows[]的数组,rows[i]表示的就是经过zigzag转换后第i行的字符串问题就能解决了。
那么进一步来说,我们只要按顺序遍历当前字符串,每经过一个字符就算出它经过zigzag转换之后处于新字符串的哪一行就行了。而算行数这个算法本身并不复杂,在纸上一画直接找规律就行。
最后我们根据rows数组重新拼接字符串就能得到答案。
Solution:
1 | public static String convert(String s, int numRows) { |