ZigZag Conversion Solutions in C++
Number 6
Difficulty Medium
Acceptance 36.4%
Link LeetCode
Other languages —
Solutions
C++ solution by haoel/leetcode
// Source : https://oj.leetcode.com/problems/zigzag-conversion/// Author : Hao Chen// Date : 2014-07-17#include <iostream>#include <vector>#include <string>using namespace std;string convert(string s, int nRows) {//The cases no need to do anythingif (nRows<=1 || nRows>=s.size()) return s;vector<string> r(nRows);int row = 0;int step = 1;for(int i=0; i<s.size(); i ++) {if (row == nRows-1) step = -1;if (row == 0) step = 1;//cout << row <<endl;r[row] += s[i];row += step;}string result;for (int i=0; i<nRows; i++){result += r[i];}return result;}int main(int argc, char**argv){string s;int r;s = "PAYPALISHIRING";r = 3;cout << s << " : " << convert(s, 3) << endl;}
C++ solution by pezy/LeetCode
#include <string>using std::string;#include <vector>#include <numeric>class Solution {public:string convert(string s, int nRows) {if (s.empty() || nRows < 2) return s;std::vector<string> ret(nRows);for (size_t i=0; i<s.size(); ++i) {int m = i % (nRows-1), n = i / (nRows-1);(n & 0x1 ? ret[nRows-m-1] : ret[m]) += s[i];}return std::accumulate(ret.cbegin(), ret.cend(), string());}};