LeetCode #6. Z字形变换 字符串处理

https://leetcode-cn.com/problems/zigzag-conversion/description/

行数为1的直接返回原串

其他情况:

设行数个空字符串,遍历原串,按照Z字型循环把字符塞进对应串,最后把串直接加起来就是结果串啦!

class Solution {

    public String convert(String s, int numRows) {

        if(numRows == 1)    //特殊情况
            return s;
        String[] str = new String[numRows + 1];
        for(int i = 1;i <= numRows;i++)
            str[i] = "";    //字符串数组初始化
        boolean tag = true; //增减标记
        int k = 0;          //字符串数组下标
        for(int i = 0;i < s.length();i++) {
            if(k == 1 && tag == false)
                tag = true;
            if(k == numRows && tag == true)
                tag = false;
            if(tag == true)
                k++;
            else
                k--;
            str[k] += s.charAt(i);
        }
        String total = "";
        for(int i = 1;i <= numRows;i++)
            total += str[i];
        return total;
    }
}

你可能感兴趣的:(LeetCode,JAVA)