leetcode—zigzag conversion

来源:互联网 发布:linux修改系统时区 编辑:程序博客网 时间:2024/06/06 05:28

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 text, int nRows);
convert(“PAYPALISHIRING”, 3) should return “PAHNAPLSIIGYIR”.

class Solution {    public String convert(String s, int numRows) {        if(s==null || numRows<=0) return null;        if(numRows==1) return s;        StringBuilder res = new StringBuilder();        int size = 2*numRows-2;        for(int i=0; i<numRows; i++){            for(int j=i; j<s.length(); j+=size){                res.append(s.charAt(j));                if(i!=0 && i!=numRows-1){                    int t = j+size-2*i;                    if(t<s.length()){                       res.append(s.charAt(t));                     }                }            }        }        return res.toString();    }}

nRows = 4
0 6 12 …
1 5 7 11
2 4 8 10
3 9
题目的意思是如上锯齿形摆放字符串,并按照行输出,这里的规律就是每2*numRows-2个字符串是一个循环,在一个循环中每一行两个相邻字符串的间隔是2*numRows-2-2i,除去首尾两行,两个循环间同一行中两个元素的间隔是2numRows-2*