6. ZigZag Conversion

来源:互联网 发布:c语言中a=3是什么意思 编辑:程序博客网 时间:2024/05/29 20:00

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


Solution:

Tips:

Try to figure out the rule of the string.

1                 7

2           6    8               12

3    5           9      11

4                 10


Java Code :

public class Solution {    public String convert(String s, int numRows) {        if (numRows == 1) {            return s;        }        char[] sc = s.toCharArray();        int[] steps = {0, 0};        StringBuilder sb = new StringBuilder();        for (int i = 0; i < numRows; i++) {            steps[1] = 2 * i;            steps[0] = 2 * (numRows - 1 - i);            int jumpSteps;            int onOff = 0;            for (int j = i; j < sc.length; j = j + jumpSteps) {                sb.append(sc[j]);                jumpSteps = steps[onOff % 2];                if (jumpSteps == 0) {                    jumpSteps = steps[(onOff + 1) % 2];                }                onOff++;            }        }        return new String(sb);    }}


0 0
原创粉丝点击