// 演算法 / Algorithm:
//   用 vector<string> 為每一列維護一個緩衝區，沿鋸齒走訪 s，
//   把每個字元 push 到「目前列」，最後一次把所有列拼接成答案。
//   Use vector<string> as per-row buffers; walk s in zigzag order;
//   push each char to its row; concatenate all rows at the end.

#include <string>   // std::string
#include <vector>   // std::vector

class Solution {
public:
    std::string convert(std::string s, int numRows) {
        int n = (int)s.size();                       // n 是輸入長度 / input length

        // 邊界：1 列沒有鋸齒；列數 >= 字元數時順序不變。直接回傳 s。
        // Edge: numRows == 1 means no zigzag; numRows >= n leaves order unchanged.
        if (numRows == 1 || numRows >= n) return s;

        // rows 是 numRows 個空字串組成的向量；每個元素代表一列的緩衝區。
        // rows is a vector of numRows empty strings; each element is one row's buffer.
        std::vector<std::string> rows(numRows);

        int cur = 0;    // 目前列索引 / current row index
        int dir = 1;    // +1 往下、-1 往上 / +1 down, -1 up
        for (char c : s) {              // range-for：依序取出 s 的每個字元 / iterate each char
            rows[cur].push_back(c);     // push_back 把字元加到字串尾端 / append to row buffer
            if (cur == 0)               dir =  1; // 頂列 → 改向下 / top → go down
            else if (cur == numRows - 1) dir = -1; // 底列 → 改向上 / bottom → go up
            cur += dir;                 // 移到下一列 / step to next row
        }

        // 依序串接所有列得到最終答案。
        // Concatenate all rows in order to form the answer.
        std::string out;
        out.reserve((size_t)n);         // 預先配置容量避免重新配置 / reserve to avoid realloc
        for (const std::string& r : rows) { // const & 避免複製 / const-ref to avoid copying
            out += r;                       // operator+= 在字串尾端 append / append in place
        }
        return out;                         // RVO/move：不會多一次拷貝 / no extra copy thanks to RVO/move
    }
};
