【LeetCode】6

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 text, int nRows);

convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".

Solution:原来是说:

1      7
2   6 8
3 5   9
要搞成折线图,然后横着输出.建nRows个数组,将s一个一个装进下标为0,1....nRows-1....1,0的数组里,两层vector
 1 class Solution {
 2 public:
 3     string convert(string s, int nRows) {
 4        if(nRows==1)return s;
 5        vector<vector<char>> vec(nRows, vector<char>());
 6        
 7        int index=-1;
 8        int tag=1;
 9        for(int i=0;i<s.size();i++){
10            index += tag;
11            vec[index].push_back(s[i]);
12            if(index==nRows-1)tag=-1;
13            else{
14                if(index==0)tag=1;
15            }
16        }
17        string ret;
18        for(int i=0;i<nRows;i++){
19            for(int j=0;j<vec[i].size();j++){
20                ret+=vec[i][j];
21            }
22        }
23        return ret;
24     }
25 };
 
原文地址:https://www.cnblogs.com/irun/p/4696748.html