LeetCode题解 第六题 N 字形变换

力扣第六题个人题解


class Solution {
public:
    string convert(string s, int numRows) {
        if(numRows == 1) return s;
        string result;
        //思路:如果numRows为4 则是3个1循环 分别为第一列满 第二列距离顶部距离为4-1 = 3 第三列距离顶部为4 - 2 = 2
        //则其共有三种位置模式:
        // P     I    N
        // A   L S  I G
        // Y A   H R
        // P     I
        //只看前三列 第一列PAYP直接排列,为模式0 然后是A,在第三列,为模式1,然后是L,为模式2
        vector<int> dis_top(numRows);//用来保存中间的位置上 每个字符到顶部的距离(纵坐标)
        //这里下标从1开始的 故上面是numRows - 1
        for(int i = 1; i < numRows - 1; i++){
            //printf("dis_top[%d]=%d\n",i,numRows - i - 1);
            dis_top[i] = numRows - i - 1;
        }
  
        vector<vector <char>> m(numRows, vector<char>(s.size(), '1'));
        //二维数组 用来保存转置后的字符串
        
        int col = 0;//转置矩阵的列指针
        int pattern = 0;//这个是模式 共有numRows - 1种:0,1,2...numRows - 1
        for(int p = 0; p < s.size();){
            if(pattern == 0){
                //cout << "pattern = 0";
                int row = 0;//转置矩阵的行指针
                for(int i = 1; i <= numRows; i++){
                    if(p == s.size()) break;//防止越界
                    //printf("row=%d col=%d char='%c'\n",row,col,s[p]);
                    m[row][col] = s[p];
                    row++;
                    p++;
                }
                col++;//到下一列
                pattern++;
                pattern = pattern % (numRows - 1);//保证pattern值正常循环
            }
            else{
                //cout << "pattern = " << pattern;
                int row = dis_top[pattern];
                //printf("row=%d col=%d char='%c'\n",row,col,s[p]);
                m[row][col] = s[p];
                p++;
                col++;
                pattern++;
                pattern = pattern % (numRows - 1);
                //保证pattern值正常循环
            }
        
        }
        //二维数组输出 debug用
        for(auto it1 : m){
            for(auto it2 : it1){
                if(it2 != '1'){
                    //cout << it2;
                    result += it2;
                }
            }
        }
        return result;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

P1nkBlood

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值