leetcode-6-zigzag conversion

Problem Description:

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".

题目大意:

给定一个字符串和一个要生成的行数,给出之字打印的结果。

Solutions:

很简单的字符串操作,利用一个辅助数组,存储每一行的结果,再依次连接起来即可。

Code in C++:

class Solution {
public:
    string convert(string s, int numRows) {
        if(s.empty()||numRows<1) return "";
        if(numRows==1) return s;
       vector<string> res(numRows);
       int i = 0;
       int j = 0;
       int dif=1;
       while(i<s.length())
       {
           res[j].push_back(s[i]);
           if(j==numRows-1){
               dif=-1;

           }else if(j==0){
               dif = 1;

           }
           j+=dif;
           i++;
       }
       string ans="";
       for(int i = 0;i<numRows;i++)
       ans+=res[i];
       return ans;
    }
};