leetcode 6. Z 字形变换(同余)

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/zigzag-conversion

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

你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"LCIRETOESIIGEDHN"。

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

string convert(string s, int numRows);

示例 1:

输入: s = "LEETCODEISHIRING", numRows = 3
输出: "LCIRETOESIIGEDHN"

示例 2:

输入: s = "LEETCODEISHIRING", numRows = 4
输出: "LDREOEIIECIHNTSG"

解:可以看到,这其实是一个mod numRows的同余系统

class Solution {
public:
    string convert(string s, int numRows) {
        int num=numRows*2-2;
        int len=s.length();
        string x="";
        if(numRows==1)return s;
        for(int i=0;i<numRows;i++){
            if(i==0||i==numRows-1)for(int j=i;j<len;j+=num){
                x+=s[j];
            }else{
                for(int j=i,k=num-i;j<len;j+=num,k+=num){
                    x+=s[j];
                    if(k>=len)break;
                    x+=s[k];
                }
            }
        }
        return x;
    }
};

猜你喜欢

转载自www.cnblogs.com/wz-archer/p/12510955.html