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

Solution:

纯粹的模拟之字形路线,时间复杂度为O(n)

题目大意:

给一个字符串,按照之字形排列成一个矩阵,然后将矩阵每一行连起来构成一个字符串,求这个字符串,题意不清,还是要给一个图才能明白
0


8


16


1

79

1517


2
6
10
14
18


35

1113

19


4


12


20

 

解题思路:

可以将之字形路线压缩,例如上例中压缩之后的到如下表所示
0
8

16





179
1517





2610
1418





3511
1319





4
12

20




 
通过这样,然后再来模拟字符串的之字形排列,要注意一些编码细节

 实现代码:
              class Solution {
public:
    string convert(string s, int nRows) {
        if(nRows==1)return s;  
        string chs=string(s);  //初始化chs为s;
        int index=0;  
        if(nRows==2)
        {  
            for(int i=0;i<s.size();i+=2)chs[index++]=s[i];  
            for(int i=1;i<s.size();i+=2)chs[index++]=s[i];  
            return chs;  
        }  
        char map[1000][1000];  
        for(int i=0;i<nRows;i++)
        {  
            for(int j=0;j<s.size();j++)  
            map[i][j]=0;  
        }  
        index=0;  
        int col=0;  
        while(s[index])
        {  
            if(col%2)
            {  
                int i=nRows-2;  
                while(i>=1 && s[index])map[i--][col]=s[index++];  
            }
            else
            {  
                int i=0;  
                while(i<nRows && s[index])map[i++][col]=s[index++];  
            }  
            col++;  //将所有的字符全部赋给map之后,col会再自加1;
        }  
        index=0;  
        for(int i=0;i<nRows;i++)
        {  
            for(int j=0;j<col;j++) //因此这里用col;
            {  
                if(map[i][j])chs[index++]=map[i][j];  
            }  
        }  
        return chs;  
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值