【Leetcode】6.Z 字形变换C++(游标法)

在这里插入图片描述
在这里插入图片描述

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

#include "iostream"
#include "string"
#include "vector"

using namespace std;

class Solution
{
public:
    string convert(string s, int numRows)
    {
        if (numRows == 1)
            return s;

        int len = s.length();
        int row_size = numRows > len ? numRows : len;

        vector<string> rows(row_size); // 保存Z中每行的字符(串)

        bool Down = false; // 遍历箭头方向,遇到0和n-1变换方向
        int row = 0;

        for (char c : s)
        {
            rows[row] += c;
            if (row == 0 || row == numRows - 1)
            {
                Down = !Down; // 转向
            }
            row += Down ? 1 : -1;
        }

        string ans;
        for (string row_s : rows)
        {
            ans += row_s;
        }

        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;
}
发布了69 篇原创文章 · 获赞 128 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_44936889/article/details/104076891