【LeetCode 面试经典150题】6. Zigzag Conversion Z 字形转换

6. Zigzag Conversion(Z 字形转换)

题目大意

The string “PAYPALISHIRING” is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

P A H N
A P L S I I G
Y I R

And then read line by line: “PAHNAPLSIIGYIR”

Write the code that will take a string and make this conversion given a number of rows:

string convert(string s, int numRows);

中文释义

字符串 “PAYPALISHIRING” 按给定行数的 Z 字形排列如上所示(为了更好的可读性,你可能希望以固定字体显示这种模式)。

然后逐行读取:“PAHNAPLSIIGYIR”

编写一个函数,接收一个字符串和行数,进行此类转换:

string convert(string s, int numRows);

示例

  • 示例 1:
    • 输入:s = "PAYPALISHIRING", numRows = 3
    • 输出:"PAHNAPLSIIGYIR"
  • 示例 2:
    • 输入:s = "PAYPALISHIRING", numRows = 4
    • 输出:"PINALSIGYAHRPI"
    • 解释:
      P     I    N
      A   L S  I G
      Y A   H R
      P     I
      
  • 示例 3:
    • 输入:s = "A", numRows = 1
    • 输出:"A"

限制条件

  • 1 <= s.length <= 1000
  • s 由英文字母(小写和大写),‘,’ 和 ‘.’ 组成。
  • 1 <= numRows <= 1000

解题思路

使用动态规划(DP)来解决问题。创建多个字符串以存储每一行的字符,并根据 Z 字形规则添加字符。

步骤说明

  1. 如果 numRows 为 1,则直接返回原字符串。
  2. 初始化一个字符串向量 rows,长度为 min(numRows, s.size())
  3. 遍历字符串 s 的每个字符:
    • 将字符添加到当前行 rows[curRow]
    • 如果当前行是第一行或最后一行,则改变方向。
    • 根据方向更新当前行 curRow
  4. 将所有行的字符串连接起来,形成最终结果。

代码

class Solution {
public:
    string convert(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 ret;
        for (string row : rows) ret += row;
        return ret;
    }
};
  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值