Leetcode 6. ZigZag Conversion

作者: SnailTyan | 来源:发表于2018-09-17 18:39 被阅读5次

    文章作者:Tyan
    博客:noahsnail.com  |  CSDN  |  简书

    1. Description

    ZigZag Conversion

    2. Solution

    • Version 1
    class Solution {
    public:
        string convert(string s, int numRows) {
            if(numRows == 1 || s.length() <= numRows) {
                return s;
            }
            string result;
            vector<string> lines(numRows);
            int row = -1;
            bool flag = true;
            for(char ch : s) {
                row = flag?++row:--row;
                lines[row] += ch;
                if(row == 0) {
                    flag = true;
                }
                else if(row == numRows - 1) {
                    flag = false;
                }
            }
            for(string line : lines) {
                result += line;
            }
            return result;
        }
    };
    
    • Version 2
    class Solution {
    public:
        string convert(string s, int numRows) {
            if(numRows == 1 || s.length() <= numRows) {
                return s;
            }
            string result;
            vector<string> lines(numRows);
            int row = -1;
            int step = 1;
            for(char ch : s) {
                row += step;
                lines[row] += ch;
                if(row == 0) {
                    step = 1;
                }
                else if(row == numRows - 1) {
                    step = -1;
                }
            }
            for(string line : lines) {
                result += line;
            }
            return result;
        }
    };
    

    Reference

    1. https://leetcode.com/problems/zigzag-conversion/description/

    相关文章

      网友评论

        本文标题:Leetcode 6. ZigZag Conversion

        本文链接:https://www.haomeiwen.com/subject/kcxagftx.html