LeetCode:ZigZag Conversion

来源:互联网 发布:机器人聊天软件 编辑:程序博客网 时间:2024/06/13 06:43

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

题目介绍:将一串字符串比如"PAYPALISHIRING",分成若干行,分配方式如下:

P   A   H   NA P L S I I GY   I   R
然后按行的先后顺序输出字符串,比如返回"PAHNAPLSIIGYIR"。

解题思路:设置一个参数记录当前行数,设置一个参数记录是处于上升还是下降状态,然后逐个把字符分配到对应行的字符串上。

代码如下:

class Solution {public:    string convert(string s, int numRows) {        if (s.length() < numRows || numRows == 1) return s;        vector<string> str(numRows);        int h = 1, up = 0;        for (int i = 0; i < s.size(); i++) {            str[h-1] += s[i];            if (up) {                h--;                if (h == 1) up = 0;            }            else {                h++;                if (h == numRows) up = 1;            }        }        string output;        for (int i = 0; i < numRows; i++) {            if (str[i].size())            for (int j = 0; j < str[i].size(); j++) {                output += str[i][j];            }        }        return output;    }};


原创粉丝点击