题目来源:
https://leetcode.com/problems/zigzag-conversion/description/
很好理解的一个题目,就是输入一个字符串,然后按照之字形排列,然后将排列好的字符串从上到下输出,根据提供的两个例子很好看出题目的要实现的功能。
Example 1:
Input: s = “PAYPALISHIRING”, numRows = 3
Output: “PAHNAPLSIIGYIR”
Explanation:
P A H N
A P L S I I G
Y I R
Example 2:
Input: s = “PAYPALISHIRING”, numRows = 4
Output: “PINALSIGYAHRPI”
Explanation:
P I N
A L S I G
Y A H R
P I
实现上可以通过动态创建输入行数的字符串,然后依次填入对应的字符,最终将这几个子串拼接输出即可,实现如下:
class Solution {
public:
string convert(string s, int numRows)
{
string *temp = NULL;
string result;
int index = 0;
temp = new string[numRows];
while(index < s.size())
{
for (int i = 0; i < numRows && index < s.size(); i++)
{
temp[i] += s[index];
index ++;
}
for (int j = (numRows - 2); j >= 1 && index < s.size(); j --){
temp[j] += s[index];
index ++;
}
}
for (int k = 0; k < numRows; k++)
{
result.append(temp[k]);
}
delete []temp;
return result;
}
};
这种实现方式提交后在LeetCode的提交时间上,处在39%的位置,不是最优的方法,还可以进行优化。