Question:

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 s, int numRows);

Example 1:

Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"

Example 2:

Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:

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

Thinking:

	class Solution {
	    public String convert(String s, int numRows) {
	        int len = 2 * numRows - 2;
	        StringBuilder[numRows] sbs = new StringBuilder[numRows];
	        for(int i = 0; i < numRows; i++){
	            sbs[i] = new StringBuilder();
	        }
	        int slen = s.length();
	        for(int i = 0; i < slen; i++){
	            int index = i % len;
	            if(index < len){
	                sbs[index].append(s.charAt(i).toString);
	            }else{
	                sbs[numRows - 1 - (index - numRows)].append(s.charAt(i).toString);
	            }
	        }
	        for(int i = 1; i < numRows; i++){
	            sbs[0].append(sbs[i].toString);
	        }
	        return sbs[0].toString;
	    }
	}

二刷

  1. 创建numRows个StringBuilder数组。
  2. 用一个游标控制每次每个字符append在哪个位置。
  3. 通过判断由标的位置判断是向上还是向下。
class Solution {
    public String convert(String s, int numRows) {
        if(s == null || s.length() == 0 || numRows == 1) return s;
        StringBuilder[] sbs = new StringBuilder[numRows];
        for(int i = 0; i < numRows; i++)
            sbs[i] = new StringBuilder();
        int len = s.length();
        int count = 0;
        int index = 0;
        boolean down = true;
        while(index < len){
            char c = s.charAt(index++);
            sbs[count].append(c);
            if(down) count++;
            else count--;
            if(count == numRows - 1 || count == 0)	//此处要注意减1。
                down = !down;
        }
        for(int i = 1; i < numRows; i++)
            sbs[0].append(sbs[i].toString());
        return sbs[0].toString();
    }
}