[LeetCode][JavaScript]ZigZag Conversion

來源:互聯網
上載者:User

標籤:

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   NA P L S I I GY   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還沒有二維數組。
 1 /** 2  * @param {string} s 3  * @param {number} numRows 4  * @return {string} 5  */ 6 var convert = function(s, numRows) { 7     var i, j; 8     if(numRows === 1){ 9         return s;10     }11     var count = 0;12     var colDirect = true;13     var row = 0, col = 0;14     var map = [];15     for(i = 0; i < s.length; i++){16         map[i] = [];17     }18     for(i = 0; i < s.length; i++){19         if(colDirect){20             map[row][col] = s[i];21             row++;22             count++;23         }else{24             map[row][col] = s[i];25             row--;26             col++;           27             count++;28         }29         if(colDirect && count === numRows){30             count = 0;31             row -= 2;32             col++; 33             colDirect = false;34         }35         if(!colDirect && count === numRows - 2){36             count = 0;37             colDirect = true;38         }39     }40     var res = "";41     for(i = 0; i < map.length; i++){42         for(j = 0; j < map[i].length; j++){43             if(map[i][j]){44                 res += map[i][j];45             }46         }47     }48     return res;49 };

 

  

[LeetCode][JavaScript]ZigZag Conversion

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.