*Leetcode - ZigZag Conversion

来源:互联网 发布:csgo启动优化参数 编辑:程序博客网 时间:2024/06/07 11:02

public class Solution {
    public String convert(String s, int nRows) {
        int l = s.length();
if (nRows >= l)
return s;
StringBuilder[] sb = new StringBuilder[nRows];
for (int z = 0; z < sb.length; z++)
sb[z] = new StringBuilder();


int k = 0, j = 0;
while (k < s.length()) {
for (int i = 0; i < sb.length && k < s.length(); i ++) {
sb[i].append(s.charAt(k++));
}
for(int i=sb.length-2; i>=1 && k < s.length(); i --){
sb[i].append(s.charAt(k++));
}

}


for (int i = 1; i < sb.length; i++) {
sb[0].append(sb[i]);
}
return sb[0].toString();
    }
}


------------------

HINT:

1. StringBuilder.append

2. StringBuilder.toString();

==========

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".
0 0
原创粉丝点击