标签:== tco for ott while etc size 题目 字符串
题目: 将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。然后横向输出。LeetCode上有几个样例可以看看。
题解:模拟一下就好了- -,对原字符串s排列完后,横向每个添加到ans中去就行了
class Solution { public: string convert(string s, int numRows) { if (numRows == 1) return s; int len = (int)s.size(), gridSize = numRows * 2 - 2; string ans = s; int pos = 0; for (int i = 0; i < numRows; ++i){ int index = i; if (index == 0 || index == numRows - 1){ while (index < len){ ans[pos++] = s[index]; index = index + gridSize; } } else{ bool bottom = true; while (index < len) { ans[pos++] = s[index]; if (bottom){ index = index + (numRows - i - 1) * 2; } else{ index = index + i * 2; } bottom = !bottom; } } } return ans; } };
标签:== tco for ott while etc size 题目 字符串
原文地址:https://www.cnblogs.com/error408/p/11610499.html