【LeetCode】 006. ZigZag Conversion

来源:互联网 发布:淘宝和亚马逊swot分析 编辑:程序博客网 时间:2024/05/22 10:31

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

public class Solution {    public String convert(String s, int nRows) {        StringBuilder[] sb = new StringBuilder[nRows];        for (int i = 0; i < nRows; i++) {            sb[i] = new StringBuilder();        }        int i = 0;        while (i < s.length()) {            for (int j = 0; j < nRows && i < s.length(); j++) {                sb[j].append(s.charAt(i++));            }            for (int j = nRows - 2; j >= 1 && i < s.length(); j--) {                sb[j].append(s.charAt(i++));            }        }        for (i = 1; i < sb.length; i++) {            sb[0].append(sb[i]);        }        return sb[0].toString();    }}


0 0
原创粉丝点击