Leetcode0006--ZigZag Conversion
阅读原文时间:2023年07月13日阅读:1

【转载请注明】https://www.cnblogs.com/igoslly/p/9017638.html

来看一下题目:

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);

Example 1:

Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"

Example 2:

Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:

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

题目意思:

给出字符串和行数

设计出一种“竖-斜”式的显示形式

结果给出按横行读取的数值

下面的图可能能更好的解释图示法:

总的来说:

1、显示法

利用代码实现zigzag这样的变形,再按读取方向输出

class Solution {
public:
string convert(string s, int numRows) {
if(numRows==){return s;}
int length = s.size(),count=;
char zigzag[numRows][length]; // 设定行、列矩阵
fill(zigzag[],zigzag[]+numRows*length,'#'); // 初始化二维数组,首位置为zigzag[0]
enum{down,linear}; // 设定方向
int dir=down,x=,y=;
while(count=numRows){dir=linear;x-=;y++;}
break;
case linear:
zigzag[x--][y++]=s[count++];
// 当斜行越界后,到达首行-1,需要进行位置调整x+2,y-1
if(x<){dir=down;x+=;y--;}
break;
}
}
string result;
for(int i=;i<numRows;i++){
for(int j=;j<length;j++){
if(zigzag[i][j]!='#'){
result+=zigzag[i][j];
}
}
}
return result;
}
};

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章