LeetCode https://leetcode.cn/problems/zigzag-conversion/
题目描述
将一个给定字符串s根据给定的行数 numRows,以从上往下、从左到右进行N字形排列。
思路
使用2维数组模拟
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| typedef std::vector<std::string> Matrix; class Solution { public: std::string convert(std::string s, int numRows) { if (s.empty() || numRows <= 1) return s; int len = (int)s.length(); Matrix matrix(numRows); int row = 0, flag = 1; for (int index = 0; index < len; ++index) { matrix[row].push_back(s[index]); row = row + flag; if (row == numRows - 1 || row == 0) flag = -flag; } std::string result; for (auto& rows : matrix) { for (auto& c : rows) result += c; } return result; } };
|