[LeetCode] 6. ZigZag Conversion

#include <iostream>
#include <string>
#include <vector>
using namespace std;

class Solution
{
public:
	string convert(string s, int numRows);
};

string Solution::convert(string s, int numRows)
{
	if (numRows == 1) {
		return s;
	}

	vector<vector<char>> rows;
	int div_num = 2 * (numRows - 1);
	int length = s.size();
	string str = "";

	for (int i = 0; i < numRows; i++) {
		vector<char> row;
		rows.push_back(row);
	}

	for (int i = 0; i < length; i++) {
		for (int j = 0; j < div_num; j++) {
			if (j < numRows) {
				if ((i - j) % div_num == 0) {
					rows[j].push_back(s[i]);
				}
			}
			else {
				if ((i - j) % div_num == 0) {
					rows[2 * (numRows - 1) - j].push_back(s[i]);
				}
			}
		}
	}

	for (int j = 0; j < numRows; j++) {
		for (int k = 0; k < rows[j].size(); k++) {
			str += rows[j][k];
		}
	}

	return str;
}


int main()
{
	Solution s;
	string str = "PAYPALISHIRING";
	cout << "old str:" << str << endl;
	str = s.convert(str, 3);
	cout << "new str:" << str << endl;
	system("pause");
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章