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
题目大意:将一串字符按照Z(N)排列,然后按行进行输出
解题思路:感觉像是大学期末考喜欢出的那种输出三角形,找出各行之间的关系就OK。对首尾两行每次只输出 i + k * num,其中 i 为行号,num为每个N的字母个数,而对于中间行,不仅要输出 i + k * num,对每个N还要输出另一个字符,关键在于找到该字符的标号的规律。
C++
class Solution {
public:
string convert(string s, int numRows) {
int len = s.length(), num = numRows == 1 ? 1 : (numRows - 1) << 1;
string ans = "";
for(int i = 0; i < numRows; ++ i){
for(int j = i; j < len; j += num){
ans += s[j];
if(i != 0 && i != numRows-1){
int temp = j+num-(i<<1);
if(temp < len)
ans += s[temp];
}
}
}
return ans;
}
};
Python
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
Len = len(s)
num = (numRows - 1) * 2 if numRows != 1 else 1
ans = ""
for i in range(numRows):
for j in range(i, Len, num):
ans += s[j]
if i != 0 and i != numRows-1:
temp = j + num - 2 * i
if temp < Len:
ans += s[temp]
return ans;