Spring Boot 2.0.0参考手册Leetcode

Leetcode 6. ZigZag Conversion

2018-09-17  本文已影响5人  SnailTyan

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

1. Description

ZigZag Conversion

2. Solution

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;
    }
};
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/
上一篇下一篇

猜你喜欢

热点阅读