首页 > 代码库 > LeetCode(6)ZigZag Conversion

LeetCode(6)ZigZag Conversion

题目如下:

技术分享

C++代码:

#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
    string convert(string s, int numRows) {
        if (numRows <= 1 || s.length() <= numRows)
            return s;
        string result;
        int ZigSpan = 2 * numRows - 2;
        for (int i = 0; i < numRows; i++){
            for (int j = i; j < s.length(); j += ZigSpan){
                result.push_back(s[j]);
                if (i != 0 && i != numRows - 1){
                    int t = j + ZigSpan - 2 * i;
                    if (t < s.length())
                        result.push_back(s[t]);
                }
            }
        }
        return result;
    }
};
void ZigZag(){
    string s = "abcdefghijklmn";
    Solution *ss = new Solution();
    cout << ss->convert(s, 3) << endl;
}

 

LeetCode(6)ZigZag Conversion