LeetCode #6 简单题(小模拟)

题目: 将一个给定字符串根据给定的行数,以从上往下、从左到右进行 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;
    }
};

 

posted @ 2019-09-29 23:16  error408  阅读(167)  评论(0编辑  收藏  举报