LeetCode【6】. ZigZag Conversion,leetcodezigzag

來源:互聯網
上載者:User

LeetCode【6】. ZigZag Conversion,leetcodezigzag

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

       題目大意為將給定字串按如上的“Z”字鋸齒形進行重排。

二、思路

       ,將該圖形進行分區。


圖一、分區圖

       從以上我們可以很清晰地根據給定字串的索引來求出其在一個“Z”型中所處的位置,是處於豎行還是斜行,是在第幾排。思路清晰,結合圖及以下代碼、注釋,可以很快明白思路。 

三、Java實現

public class Solution {    public String convert(String s, int numRows) {        int sl = s.length();        if(numRows<=1||sl<=numRows)                                   return s;                int N = (int)Math.ceil((double)sl/(2*numRows-2));  //1. 計算分區大小,最後一個區可能是充滿也可能是不滿,所以向上取整        int index1=0, index2=0;        int nN = 2*numRows-2;                              //2. 求出一分區內有多少元素。豎行是numRows個,斜行需減去頭尾兩個元素        StringBuffer sb = new StringBuffer();                for(int iR = 1; iR<=numRows; iR++)                 //3. 按行進行掃描輸出        {            for(int jN = 1; jN<=N; jN++)                   //4. 掃描iR行的不同分區              {            //4.1. index1為第jN塊的第iR行豎值索引                index1 = (jN-1)*nN + iR;                                                      if(index1<=sl)                {                    sb.append(s.charAt(index1-1));                        }               //4.2. index2為第jN塊的第iR行斜值索引,斜行去迴轉尾兩個                if((iR!=1)&&(iR!=numRows))                   {                  index2 = (jN-1)*nN + 2*numRows -iR;                                    if(index2<=sl)                  {                sb.append(s.charAt(index2-1));                                  }                }              }        }        return sb.toString();    }}



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.