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

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

开始采用了string.push_back,出现内存溢出,换为string+=就可以通过。

锯齿状走线,除去头尾都是step=2*(nROW-1);其他都为i,step-i,交替输入。

 1 class Solution {
 2 public:
 3     string convert(string s, int numRows) {
 4         int n=s.size();
 5         if(n<2) return s;
 6         if(numRows==1) return s;
 7         int step=(numRows-1)*2;
 8         string res="";
 9             for(int j=0;j<numRows;j++)
10             {
11                 int left=j;
12                 int right=step-j;
13                 if(right==step||left==right)
14                 {
15                     while(left<n)
16                     {
17                         res+=s[left];
18                         left+=step;
19                         
20                     }
21                 }
22                 else
23                 {
24                     while(left<n||right<n)
25                     {
26                         if(left<n)
27                         {
28                             res+=s[left];
29                             left+=step;
30                             
31                         }
32                         if(right<n)
33                         {
34                             res+=s[right];
35                             right+=step;
36                         
37                         }
38                     }
39                 }
40             }
41         
42         return res;
43     }
44 };

 另一种解法:

建立一个大小为 numRows 的字符串数组,为的就是把之字形的数组整个存进去,然后再把每一行的字符拼接起来,就是想要的结果了。顺序就是按列进行遍历,首先前 numRows 个字符就是按顺序存在每行的第一个位置,然后就是 ‘之’ 字形的连接位置了。

也就是先竖着放一边,再返回去放一边中间位置,算是一次循环。然后重复这个循环。

class Solution {
public:
    string convert(string s, int nRows) {
        vector<string> v(nRows);
        int pos=0;
        int i=0;
        int n=s.size();
        while(i<s.size())
        {
            for(pos=0;pos<nRows&&i<n;++pos)
                v[pos]+=s[i++];
            for(pos=nRows-2;pos>=1&&i<n;--pos)
                v[pos]+=s[i++];
        }
        string res;
        for(int j=0;j<nRows;++j)
            for(int k=0;k<v[j].size();++k)
                res+=v[j][k];
        return res;
    }
};
原文地址:https://www.cnblogs.com/zl1991/p/4715286.html