[Leetcode] 6.Z shaped transform C ++ (Direct Sorting)

Here Insert Picture Description

Here Insert Picture Description

/*
将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。
*/
#include "iostream"
#include "string"

using namespace std;

class Solution
{
public:
    string convert(string s, int numRows)
    {
        int cols, spare, i, j, part, size = s.size();

        if (numRows == 1)
        {
            return s;
        }

        part = 2 * numRows - 2;                 // 没一小部分有多少个
        cols = s.size() / part * (numRows - 1); // 有多少整列
        spare = s.size() % part;                // 散列中多出来多少个

        if (spare > 0)
        {
            cols += 1;
            if (spare > numRows)
            {
                cols += spare - numRows;
            }
        }

        string ans;
        char c;

        for (i = 0; i < numRows; i++)
        {
            for (j = 0; j < cols; j++)
            {
                if (j % (numRows - 1) == 0 && part * (j / (numRows - 1)) + i < size)
                {
                    c = s[part * (j / (numRows - 1)) + i];
                    cout << c;
                    ans.push_back(c);
                }
                else if (j % (numRows - 1) == numRows - i - 1 && part * (j / (numRows - 1)) + 2 * numRows - i - 2 < size)
                {
                    c = s[part * (j / (numRows - 1)) + 2 * numRows - i - 2];
                    cout << c;
                    ans.push_back(c);
                }
                else
                {
                    cout << " ";
                }
            }
            cout << endl;
        }
        return ans;
    }
};

int main()
{
    string s;
    int numRows;

    cin >> s;
    cin >> numRows;

    Solution so;
    string ans = so.convert(s, numRows);

    cout << ans << " " << ans.size() << endl;
    return 0;
}
Published 68 original articles · won praise 128 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_44936889/article/details/104076630