LeetCode-6.Z 字形变换(ZigZag Conversion)

6.Z 字形变换(ZigZag Conversion)

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


示例 1:

输入: s = “LEETCODEISHIRING”, numRows = 3
输出: “LCIRETOESIIGEDHN”
解释:
L C I R
E T O E S I I G
E D H N

示例 2:

输入: s = “LEETCODEISHIRING”, numRows = 4
输出: “LDREOEIIECIHNTSG”
解释:
L D R
E O E I I
E C I H N
T S G


源代码:

class Solution {
public:
    string convert(string s, int numRows) {
        if(s.length() == 0 || numRows == 1 || numRows > s.length()){
        	return s;
        }
        string temp[numRows];
        string res;
        int length = s.length();
        int num = -1;
        int row = 0;
        for(int i = 0; i < length; i++) {
        	if(row == 0 || row == numRows - 1) {
        		num *= -1; 
        	}
        	temp[row] += s[i];
        	row += num;
        }
        for(int i = 0; i < numRows; i++) {
        	res += temp[i];
        }
        return res;
    }
};

题目链接:https://leetcode-cn.com/problems/zigzag-conversion/

发布了42 篇原创文章 · 获赞 2 · 访问量 1431

猜你喜欢

转载自blog.csdn.net/Listen_heart/article/details/101272727