6. ZigZag Conversion

题目

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

设置numRows个数组,按照顺序依次添加到对应数组中;同时设置步长,用来修改对应的行号:
row == 0: step=1(依次往下,row++);row == numRows-1: step=-1(到最后一行,依次往上,row--行号递减)
row += step;
最后将各行结果依次添加到新字符串中.
将各行结果存储在对应字符串中,不用计算转换后的下标,然后拼接最终结果了.
pros & cons: 容易理解; 浪费存储空间

class Solution {
public:
    string convert(string s, int numRows) {
        if(numRows < 2) return s;
        int len = s.size();
        string* str = new string[numRows];
        int row = 0, step = 1;
        for(int i=0;i

你可能感兴趣的:(6. ZigZag Conversion)