6. Z 字形变换

1.Description

将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。

比如输入字符串为 "PAYPALISHIRING" 行数为 3 时,排列如下:

P   A   H   N
A P L S I I G
Y   I   R
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"PAHNAPLSIIGYIR"。

请你实现这个将字符串进行指定行数变换的函数:

string convert(string s, int numRows);

2.Example

输入:s = "PAYPALISHIRING", numRows = 4
输出:"PINALSIGYAHRPI"
解释:
P     I    N
A   L S  I G
Y A   H R
P     I

3. My Code(二维数组)

class Solution {
public:
    string convert(string s, int numRows) {
        int n = s.length();
        int numCols = n;
        vector<vector<char>> v(numRows,vector<char>(numCols,'0'));
        int col=0;
        //对于只有1行的,循环出不来,直接返回
        if(numRows ==1)
            return s;
        //col表示列,j表示行
        for(int i=0;i<n;i=i+(2*numRows-2)){
            int j=0;
            for(j=0;j<numRows;j++){
                if(i+j >= n){
                    break;
                }
                v[j][col] = s[i+j];
            }
            j--;
            for(int k=0;k<numRows-2;k++){
                j--;
                col++;
                if(i+numRows+k >= n){
                    break;
                }
                v[j][col] = s[i+numRows+k];
            }
            col ++;
        }
        string res="";
        for(int i=0;i<numRows;i++)
            for(int j=0;j<numCols;j++){
                if(v[i][j]!='0')
                    res+=v[i][j];
            }
        return res;   
    }
};

4.Code

左到右按箭头方向迭代 s ,将每个字符添加到合适的行。之后从上到下遍历行。

构建多个行,然后遍历字符串s,依次为不同行填上对应的字符。

class Solution {
public:
    string convert(string s, int numRows) {
        int n = s.length();
        if(numRows < 2)
            return s;
        vector<string> v(numRows);
        bool down = false;
        int currRow = 0;
        for(char c:s){
            v[currRow] += c;
            if(currRow ==0 || currRow == numRows-1)
                down = !down;
            currRow += down?1:-1;
        }
        string res;
        for(string str:v)
            res += str;
        return res;
    }
};

5.注意

1.对于只有一行的,直接返回。

2.使用一维数组,用布尔变量控制行数的走向,确实比用二维数组厉害的多。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值