6. ZigZag Conversion

来源:互联网 发布:淘宝上显示喵喵折 编辑:程序博客网 时间:2024/06/05 17:20

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 1 Straightforward way
16ms 36.11%
public class Solution {    public String convert(String s, int numRows) {        if(s == null || s.length() < 2 || numRows < 2){            return s;        }        List<StringBuilder> list = new ArrayList<StringBuilder>();        for(int i = 0; i < numRows; i++){            list.add(new StringBuilder());        }        boolean goingDown = true;        int index = 0;        for(int i = 0; i < s.length(); i++){            char c = s.charAt(i);            list.get(index).append(c);                        if(goingDown){                if(index == numRows - 1){                    goingDown = false;                    index--;                }else{                    index++;                }            }else{                if(index == 0){                    index = 1;                    goingDown = true;                }else{                    index--;                }            }        }        StringBuilder res = new StringBuilder();        for(StringBuilder sb : list){            res.append(sb.toString());        }        return res.toString();    }}

0 0
原创粉丝点击