题解 | #牛牛的旗语传递#
牛牛的旗语传递
https://www.nowcoder.com/practice/810b1c80a9c341c4af69facac350d6bc
考察的知识点:字符串;
解答方法分析:
- 创建一个长度为numRows的字符串数组,每个元素代表当前行的字符。
- 遍历加密字符串,将每个字符依次添加到对应的行中。
- 行数的变化通过一个布尔量goingDown和一个当前行的索引curRow来控制。
- 将每一行拼接起来,就得到了解码后的字符串。
所用编程语言:C++;
完整编程代码:↓
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @param numRows int整型 * @return string字符串 */ string decodeFlag(string s, int numRows) { if (numRows == 1) { return s; } vector<string> rows(min(numRows, int(s.size()))); int curRow = 0; bool goingDown = false; for (char c : s) { rows[curRow] += c; if (curRow == 0 || curRow == numRows - 1) { goingDown = !goingDown; } curRow += goingDown ? 1 : -1; } string result; for (string row : rows) { result += row; } return result; } };