您的位置:首页 > Web前端 > JavaScript

[LeetCode][JavaScript]ZigZag Conversion

2015-05-31 18:17 591 查看

ZigZag Conversion

The string
"PAYPALISHIRING"
is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

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

And then read line by line:
"PAHNAPLSIIGYIR"


Write the code that will take a string and make this conversion given a number of rows:

string convert(string text, int nRows);

convert("PAYPALISHIRING", 3)
should return
"PAHNAPLSIIGYIR"
.

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

号称easy,我怎么感觉并不是很水...
colDirect标记是走竖的还是走斜的,根据情况调整下标。
该死的js还没有二维数组。

/**
* @param {string} s
* @param {number} numRows
* @return {string}
*/
var convert = function(s, numRows) {
var i, j;
if(numRows === 1){
return s;
}
var count = 0;
var colDirect = true;
var row = 0, col = 0;
var map = [];
for(i = 0; i < s.length; i++){
map[i] = [];
}
for(i = 0; i < s.length; i++){
if(colDirect){
map[row][col] = s[i];
row++;
count++;
}else{
map[row][col] = s[i];
row--;
col++;
count++;
}
if(colDirect && count === numRows){
count = 0;
row -= 2;
col++;
colDirect = false;
}
if(!colDirect && count === numRows - 2){
count = 0;
colDirect = true;
}
}
var res = "";
for(i = 0; i < map.length; i++){
for(j = 0; j < map[i].length; j++){
if(map[i][j]){
res += map[i][j];
}
}
}
return res;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: