Code29 Z字形变换

博客围绕LeetCode6的Z字形变换题目展开。题目要求将给定字符串按指定行数进行Z字形排列后逐行读取生成新字符串。给出了示例输入输出,还阐述了代码思路,如根据行数不同处理逻辑不同,对每组元素按特定规则存储,最后串联结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

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

比如输入字符串为 “LEETCODEISHIRING” 行数为 3 时,排列如下(为显示整齐增加-):
L----------C-----------I---------R
E----T----O----E----S----I----I----G
E----------D----------H--------N
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:“LCIRETOESIIGEDHN”。

请你实现这个将字符串进行指定行数变换的函数:
string convert(string s, int numRows);

示例 1:
输入: s = “LEETCODEISHIRING”, numRows = 3
输出: “LCIRETOESIIGEDHN”

示例 2:
输入: s = “LEETCODEISHIRING”, numRows = 4
输出: “LDREOEIIECIHNTSG”

代码
  • 思路
    • 若 numRows <= 0, 直接返回空string;
    • 若 numRows == 1, 直接返回 s;
    • 若 numRows >= 2, 能发现其实对每个 “对勾√”形的一组元素(例如 numRows == 3时每4个元素, 每组元素数= 2 * numRows - 2)处理逻辑相同;
    • 创建具有 numRows 个元素的字符串 vector temp_vc, 每个字符串存储一行元素;
    • 对于每组 2 * numRows - 2 个元素,假设 某元素在原字符串 s 中的下表为 i, 则有:
      • 假设该元素是组中的第 index 个 元素,则有 index = i % (numRows * 2 - 2);进一步分析:
        • index < numRows ( “对勾√”形中的 |)时,temp_vc[index] += s[i];
        • index >= numRows ( “对勾√”形中的 /)时, temp_vc[2 * (numRows - 1) - index] += s[i];
    • 最后将 temp_vc 中的字符串串联起来为最终结果。
  • 代码
#include <string>
#include <vector>
using namespace std;

// char* convert(char* s, int numRows) {}

class Solution {
 public:
  string convert(string s, int numRows) {
    if (numRows <= 0) {
      return string();
    } else if (1 == numRows) {
      return s;
    } else {
      string res;
      vector<string> temp_vc(numRows);

      for (int i = 0; i < s.size(); ++i) {
        int index = i % (numRows * 2 - 2);
        if (index < numRows) {
          temp_vc[index] += s[i];
        } else {
          temp_vc[2 * (numRows - 1) - index] += s[i];
        }
      }

      for (auto& str : temp_vc) {
        res += str;
      }

      return res;
    }
  }
};
测试
#include <iostream>
int main() {
  Solution s;
  string str = "LEETCODEISHIRING";

  cout << s.convert(str, 3);

  cin.get();
  return 0;
}
  • 结果
LCIRETOESIIGEDHN
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值