【Leetcode】6. ZigZag Conversion

来源:互联网 发布:js ajax同步和异步的 编辑:程序博客网 时间:2024/06/05 06:36

思路:

(1)定义一个长度为numRows的数组,存放每一行得到的字符串;

(2)数组下标先递增,直到numRows-1,则反向,直到0,再反向,……直到s字符全部装入数组

(3)依次输出数组中0~nRows-1位置的字符串。

public class Solution {    public String convert(String s, int numRows) {    if (numRows == 1)       return s;        String result = "";        String[] res = new String[numRows];        int len = s.length();        for (int i = 0; i < numRows; i++)             res[i] = "";        int flag = 0, row = 0;        for (int i = 0; i < len; i++) {            res[row] += s.charAt(i);            if (row == numRows - 1)            flag = 1;            if (row == 0)            flag = 0;            if (flag == 0)            row++;            else            row--;        }        for (int i = 0; i < numRows; i++)             result += res[i];        return result;    }}
时间复杂度:O(n)

Runtime: 82ms

注意:Java String必须初始化为"",未被初始化的字符串执行"+"操作后打印出的字符串最前面是null

String str = null;str += "Hello";System.out.println(str);//nullhello

String str = "";str += "Hello";System.out.println(str);//hello

1 0