问题描述
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;
}
结果展示