您的位置:首页 > 其它

[leetcode] ZigZag Conversion *

2013-03-09 00:21 357 查看
/*
* Just find the rule; Do not forget to check
* special cases (e.g. nRows = 1 ...)
*
* @author: HZT
* @date: 2013-3-9
*/

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

class Solution {
public:
string convert(string s, int nRows) {
// Start typing your C/C++ solution below
// DO NOT write int main() function

// DO NOT forget this!!
if(nRows == 1) return s;
if(s.empty()) return s;
int len = s.length();

char* ans = new char[len+1];

int idx, ansIdx=0;
int delta = 2 * nRows - 2;
// each row
for(int r=1; r<=nRows; r++){
idx = r;
while(idx <= len){
ans[ansIdx++] = s[idx-1];
if(r!=1 && r!=nRows && 2*nRows-2*r+idx <= len){
ans[ansIdx++] = s[2*nRows-2*r+idx-1];
}

idx += delta;
}
}

ans[len] = '\0';
return ans;
}
};

int main(){
string s = "PAYPALISHIRING";
int nRows = 3;

//string s = "A";
//int nRows = 1;

cout << (new Solution)->convert(s, 3) << endl;

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: