[Java]leetcode6 ZigZag Conversion

來源:互聯網
上載者:User

標籤:leetcode

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".

題意是:給你一個字串,他是以Z形式表示出來的字串順序,然後你以行的形式讀出來。給定了字串的行數。

解題思路:我們發現第一行和最後一行都很好處理,就是每次讀取j+2*nRows-2,就是中間的行則需要單獨處理。

正如以上的例子,我們發現,我們可以每次選區PAYP作為一個單元處理。就是選取nRows+nRows-2=2nRows-2個長度處理。

那麼中間元素的位置關係是j+2*nRows-2i-2(i表示第幾行)

ok,代碼如下:

public String convert(String s, int nRows){if (s == null || nRows == 1)return s;int len = s.length();if (len <= nRows)return s;StringBuffer res = new StringBuffer();int size = 2 * nRows - 2;//每次處理的長度for (int i = 0; i < nRows; i++) {//每一行的元素char ch;for (int j = i; j < len; j += size) {ch = s.charAt(j);res.append(ch);if (i != 0 && i != nRows - 1) {//如果是中間元素單獨處理int tmp = j + size - 2 * i;if (tmp < len) {ch = s.charAt(tmp);res.append(ch);}}}}return res.toString();}


[Java]leetcode6 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.