leetcode zig-zag conversion

* ZigZag.js

/*
https://leetcode.com/problems/zigzag-conversion/

"PAYPALISHIRING"
row x 3

P   A   H   N
A P L S I I G
Y   I   R
*/

function ZigZag() {}

String.prototype.forEach = function(fn) {
    for (var i = 0; i < this.length; i++) {
	fn( this.charAt(i) );
    }
};

ZigZag.convert = function(/* String */ s, /* Number */ numRows) {
    if (numRows === 1) {
	return s;
    }
    var rows = [], n = Math.min(numRows, s.length);
    for (var i = 0; i < n; i++) {
    	rows[i] = "";
    }

    var curRow = 0, goingDown = false;
    s.forEach(function(c) {
	// rows[curRow] += c;
	rows[curRow] = rows[curRow] ? rows[curRow] + c : "" + c;
	
	if (curRow === 0 || curRow === numRows - 1) {
	    goingDown = ! goingDown;
	}
	curRow += goingDown ? 1 : -1;
    });
    console.debug(rows);
    return rows.join("");
};

ZigZag.convert2 = function(/*String */s, /*Nubmer */ numRows) {
    if (numRows === 1) {
	return s;
    }
    var ret = "";
    var n = s.length;
    var cycleLen = 2 * numRows - 2;
    
    for (var i = 0; i < numRows; i++) {
	for (var j = 0; j + i < n; j += cycleLen) {
	    ret += s.charAt(j+i);
	    if (i !== 0 && i !== numRows - 1 && j + cycleLen - i < n) {
		ret += s.charAt( j + cycleLen - i );
	    }
	}
    }
    return ret;
};

ZigZag.convert3 = function(s, numRows) {
    if (numRows === 1) { return s;}
    
    var n = s.length;
    var b = "";
    for (var i = 0; i < numRows; i++) {
	for (var j = i;  j < n; ) {
	    b += s.charAt(j);
   	    // We set j to the next value in the same row and the next column
	    j += numRows + numRows - 2;
    	    // If current row is 0 or numRows - 1 there is no element in the diagonal between columns to consider
	    if (i === 0 || i === numRows-1) {
		continue;
	    }
	    // Set j to the value in the same row and in the diagonal between and next column
	    j -= i + i
	    // Validate that j is a valid index
	    if (j >= n) {
		break;
	    }
	    b += s.charAt(j);
	    // Set j back again to the value in the same row and the next column
	    j += i + i;
	}
    }
    return b;
};

test:

var s = "PAYPALISHIRING";
console.log( ZigZag.convert(s, 3) );  // "PAHNAPLSIIGYIR"
console.log( ZigZag.convert2(s, 4) ); // "PINALSIGYAHRPI"
console.log( ZigZag.convert3(s, 3) );  // "PAHNAPLSIIGYIR"

node ZigZag.js

[ 'PAHN', 'APLSIIG', 'YIR' ]

PAHNAPLSIIGYIR

PINALSIGYAHRPI

PAHNAPLSIIGYIR

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fareast_mzh

打赏个金币

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值