一、题目(来源:leetcode):
二、分析
我自己的做法是将对于Z字形排列的每一行,遍历字符串,然后根据下标与numRows的关系加到result字符串中,这样空间复杂度为O(1),但是这样时间复杂度是O(m*n)。
代码:
class Solution {
public:
string convert(string s, int numRows) {
string result = "";
if(numRows == 1) return s;
for(int i = 0; i < numRows; i ++){
for( int j = 0; j < s.size(); j ++){
if(j % (2*numRows-2) == i || j % (2*numRows-2) == (2*numRows-2) - i) {
result += s[j];
}
}
}
return result;
}
};
结果:
执行用时:100 ms, 在所有 C++ 提交中击败了7%的用户
内存消耗:7.9 MB, 在所有 C++ 提交中击败了96%的用户
然后看解析发现一种以空间换时间的算法,新建一个vector,首先遍历字符串,按照下标与numRows的关系将每个字符排序到vector中,最后将其取出构建新的字符串。
class Solution {
public:
string convert(string s, int numRows) {
string result = "";
if(numRows == 1) return s;
vector<string> temp(numRows);
for(int i = 0; i < s.length(); i++){
int ans = i / (numRows-1);
int cur = i % (numRows-1);
if(ans % 2 == 0){ //结果为偶数或0
temp[cur].push_back(s[i]); //按余数正序保存
}
if(ans % 2 != 0){ //结果为奇数
temp[numRows-cur-1].push_back(s[i]); //按余数倒序保存
}
}
for(int i = 0; i < temp.size(); i++){
result += temp[i];
}
return result;
}
};
这样时间复杂度为O(n),空间复杂度为O(n)。
结果:
执行用时:4 ms, 在所有 C++ 提交中击败了98.48%的用户
内存消耗:10.5 MB, 在所有 C++ 提交中击败了52.68 %的用户