leetcode---(6).Z 字形变换

将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 “PAYPALISHIRING” 行数为 3 时,排列如下:

P   A   H   N
A P L S I I G
Y   I   R
输入:s = "PAYPALISHIRING", numRows = 3
输出:"PAHNAPLSIIGYIR"
class Solution {
public:
    string convert(string s, int numRows) {
        if(numRows == 1 || s.length() == 1)
            return s;
        
        vector<vector<char>> matrix(numRows,vector<char>(s.length()/2 + 1));
        int k = 0, i = 0, j=0;

        while(k < s.length()){
            for(;(i < numRows) && (k < s.length()); i++){
                matrix[i][j] = s[k];
                k++;
            }
            i--;
            i--;j++;
            for(;(i > 0) && (k < s.length()); i--,j++){
                matrix[i][j] = s[k];
                k++;
            }
        }
        string output = "";
        vector<vector<char>>::iterator row_it;
        vector<char>::iterator         col_it;
        for(row_it = matrix.begin();row_it != matrix.end();row_it++){
            for(col_it = (*row_it).begin();col_it < (*row_it).end();col_it++){
                if(*col_it != NULL)
                    output += *col_it;
            }
        }
        return output;
    }
};

感觉写的比较啰嗦,但也不知道怎么改。还有边界意识,提交了三次修修改改才过。我们看看官方的。

//模仿添加的过程
class Solution {
public:
    string convert(string s, int numRows) {

        if (numRows == 1) return s;

        vector<string> rows(min(numRows, int(s.size())));
        int curRow = 0;
        bool goingDown = false;

        for (char c : s) {
            rows[curRow] += c;
            if (curRow == 0 || curRow == numRows - 1) goingDown = !goingDown;
            curRow += goingDown ? 1 : -1;
        }

        string ret;
        for (string row : rows) ret += row;
        return ret;
    }
};
//数学归纳法
class Solution {
public:
    string convert(string s, int numRows) {

        if (numRows == 1) return s;

        string ret;
        int n = s.size();
        int cycleLen = 2 * numRows - 2;

        for (int i = 0; i < numRows; i++) {
            for (int j = 0; j + i < n; j += cycleLen) {
                ret += s[j + i];
                if (i != 0 && i != numRows - 1 && j + cycleLen - i < n)
                    ret += s[j + cycleLen - i];
            }
        }
        return ret;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值