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;
    }
};
复制代码

 

posted @   鸭子船长  阅读(154)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示