6. Zigzag Conversion

problem

solution

mod

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
string convert(string s, int numRows) {
if(numRows==1) return s;
vector<string> nums(numRows);
int period = 2*numRows-2;
for(int i=0;i<s.size() ; ++i){
int mod = i%period;
if(mod < numRows) nums[mod]+=s[i];
else nums[period-mod]+=s[i];
}
string ret;
for(string str:nums) ret+=str;
return ret;
}
};

analysis

  • time complexity O(n)
  • space complexity O(n)