coding
unsky
deepdim
thought

ZigZag Conversion 回旋字符串

id:6. ZigZag Conversion QuestionEditorial Solution My Submissions
Total Accepted: 120341
Total Submissions: 469716
Difficulty: Easy
Contributors: Admin
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)


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 text, int nRows);
convert(“PAYPALISHIRING”, 3) should return “PAHNAPLSIIGYIR”.
Subscribe to see which companies asked this question

这道题是一个变换,只要找到其中的规律就很好做题。

假设结果存在一个string result中

原字符串存于s

经过观察我们可以发现
红色部分的变换为:

result.append(1,s[j*(numRows+numRows-2)+i])

绿色部分的变换为

result.append(1,s[(j+1)*(numRows+numRows-2)-i])

其中i是第i行,j是(红色或者绿)的第j个数

所以我们可以这么写代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public:
string convert(string s, int numRows) {
string result;
if (numRows==1)
return s;
if(s.size()==0)return result;
for(int i=0;i<numRows;i++)
{
for(int j=0;(j*(numRows+numRows-2)+i)<s.size();j++)
{result.append(1,s[j*(numRows+numRows-2)+i]);
if(i==0||i==numRows-1)
continue;
if(((j+1)*(numRows+numRows-2)-i)<s.size())
{
result.append(1,s[(j+1)*(numRows+numRows-2)-i]);
}
}
}
return result;
}
};

坚持原创技术分享,您的支持将鼓励我继续创作!