6:ZigZag Conversion(锯齿形的转换)

本文介绍了如何将字符串按照Z字形排列并按行读取,以'PAYPALISHIRING'为例,当行数为3时,转换后的字符串为'PAHNAPLSIIGYIR'。解题思路包括使用字符串数组按特定顺序存储字符,然后组合成最终结果。

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

问题描述
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 text, int nRows);

convert(“PAYPALISHIRING”, 3) should return “PAHNAPLSIIGYIR”.

解题思路
该问题的描述比较简单,输入一个字符串,然后将其按照给定的行数成“Z”字型排列,然后重新输出即可。这样说可能不够明白,所以可以按下图所示:
这里写图片描述
输入的字符串为“ABCDEFGHIJKLM”,给定的行数是5,则将字符串按照上图的顺序排列,然后输出的结果为“AIBHJCGKDFLEM”,即按照排列后的行输出。解决该问题的方法也很简单,我们可以申请空间为给定行数的字符串数组,然后将字符串的字符依次添加到字符串数组中,数组下标依次递增,到达下标上限则递减,直至将字符串的每个字符都赋值给数组,最后将所得到的字符串数组整合成一个字符串。
代码展示

#include <iostream>
#include <stdlib.h>
#include <string.h>
using namespace std; 

class Solution {
public:
    string convert(string s, int numRows) {
        int size = s.length();              //获取字符串长度 
        if(size==0 || numRows<=1) return s; 
        string *str=new string[numRows];    //申请空间为行数的字符串数组 
        int flag=1;                         //flag表示数组下标的增量 
        int row=0;      
        for(int i=0;i<size;i++){
            str[row]+=s[i];                //依次给字符串数组赋值 
            row = row+flag;
            if(row >= numRows){  
                row = numRows-2;           //到达最后改变数组的增量 
                flag = -1;  
            }  
            if (row < 0){              
                row = 1;  
                flag = 1;  
            }  
        }
        string result;
        for(int i=0;i<numRows;i++){       //整合所得到的字符串数组 
            result += str[i];
        }
        return result;
    }
};
int main(){
    string s;
    int num;
    cin>>s>>num;
    Solution so;
    string str=so.convert(s,num);
    cout<<str<<endl;
    return 0;
}

结果展示
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值