LeetCode 6. Z字形变换 ZigZag Conversion

将字符串 "PAYPALISHIRING" 以Z字形排列成给定的行数:

P   A   H   N
A P L S I I G
Y   I   R

之后从左往右,逐行读取字符:"PAHNAPLSIIGYIR"

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

string convert(string s, int numRows);

示例 1:

输入: s = "PAYPALISHIRING", numRows = 3
输出: "PAHNAPLSIIGYIR"

示例 2:

输入: s = "PAYPALISHIRING", numRows = 4
输出: "PINALSIGYAHRPI"
解释:

P     I    N
A   L S  I G
Y A   H R
P     I

 

static const auto ____ = []() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    return nullptr;
}();
class Solution {
public:
    string convert(string s, int numRows) {
        if(s == "")//为空返回空
            return "";
        if(numRows == 1)//一行,就返回一行
            return s;
        string ans = "";//输出答案
        bool goingdown = false;//方向
        string rows[numRows];//存每行的字符串
        for(int i = 0; i < numRows; ++i)//初始化每一行
            rows[i] = "";
        int curRow = 0;//当前行
        for(int i = 0; i < s.length(); ++i)//一个一个字符来
        {
            rows[curRow]+=s[i];//当前行的字符
            if(curRow == 0 || curRow == numRows - 1) goingdown = !goingdown;//为0或者到底就要换方向
            curRow += goingdown?1:-1;//看方向是什么,往下就+1
        }
        for(int i = 0; i < numRows; ++i)//把字符串合并
            ans += rows[i];
        return ans;
    }
};

 

static const auto ____ = []() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    return nullptr;
}();
class Solution {
public:
    string convert(string s, int numRows) {
        if(s == "")//为空返回空
            return "";
        string ans = "";//返回答案
        int x = 2 * numRows - 2;//间隔
        int len = s.length();//字符串长度
        if(numRows == 1)//行数为1直接返回
            return s;
            
        for(int i = 0; i < numRows; ++i)//第i行
        {
            for(int j = 0; j + i < len; j+=x)//从第i+j开始,每次j+x
            {
                ans += s[j+i];//把字符附到答案后
                if(i != 0 && i != numRows - 1 && j + x - i < len)//当不是首末两行时还要加上j+x-i 可以理解为只有一个字符的列的排列规律,即第j+x列减去i就是那列的字符位置
                    ans += s[j + x - i];
            }
        }
        return ans;
    }
};

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值