6. Z 字形变换题解

原题:https://leetcode-cn.com/problems/zigzag-conversion/
法一:直接模拟法
以一竖一斜为一个周期,周期t=r+r-2
用二维数组记录模拟数组再读取输出

class Solution {
public:
    string convert(string s, int numRows) {
        int n = s.size(), r = numRows;
        if(numRows == 1 || r >= n) return s;
        int t = 2 * r - 2;
        int col = (n + t - 1) / t * (r - 1); // n/t向上取整 
        vector<string> mat(r, string(col, 0));
        for(int i = 0, x = 0, y = 0;i < n;i++) {
            mat[x][y] = s[i];
            if(i % t < r - 1) {
                x++;
            }
            else {
                x--;
                y++;
            }
        }
        string ans;
        for (auto &row : mat) {
            for (char ch : row) {
                if (ch) {
                    ans += ch;
                }
            }
        }
        return ans;
    }
};

注意计算列col值时的计算顺序,否则容易超时

法二:模拟优化
模拟的二维数组中有许多空闲位置造成了浪费,用一维数组模拟降低消耗。

class Solution
{
public:
    string convert(string s, int numRows)
    {
        if (numRows == 1)
        {
            return s;
        }
        int sSize = int(s.size());
        int storeSize = min(sSize, numRows);
        string result;
        vector<string> store(storeSize);
        int loc = 0;
        //初始有一次更改change值,因此初始值为false
        bool change = false;
        for (int index = 0; index < sSize; index++)
        {
            store[loc].push_back(s[index]);
            if (loc == numRows - 1 || loc == 0)
            {
                change = !change;
            }
            loc += change ? 1 : -1;
        }
        for (int index = 0; index < storeSize; index++)
        {
            result = result + store[index];
        }
        return result;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值