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个数
所以我们可以这么写代码: