標籤: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