LeetCode解题报告--ZigZag Conversion

LeetCode解题报告--ZigZag Conversion_第1张图片
题目来源:https://leetcode.com/problems/zigzag-conversion/

P AH N
AP LS I I G
YI R
解法一:
间距为: icount = 2 * (nRows - 1)
每列的字符个数为:i = nRows[from 0 to (nRows - 1)]
中间未加粗字符其下标为: mid = j + icount - 2 * i (j : from 0 to s.length() - 1)

public static String convert(String s, int numRows) {
        int icount = 2 * (numRows - 1);
        String newStr = "";
        if(numRows < 2 || s.length() <= 1)
            return s;
        else{
            for(int i = 0;i < numRows;i ++){

                for(int j = i;j < s.length();j += icount){
                    newStr += s.charAt(j);
                    int mid = j + icount - 2 * i;

                    if(i != 0 && i != numRows - 1 && mid >= 0 && mid < s.length()){
                        newStr += s.charAt(mid);
                    }
                }
            }
            return newStr;
        }

    }

解法二:
将每层看层一个字符串,则共有nRows字符串,最后将其依次输出即可。
public static String convert(String s, int numRows) {

        StringBuffer[] str = new StringBuffer[numRows];
        boolean down = true;
        int j = 0;
        if(s.length() <= 1 || numRows <= 1)
            return s;

        for(int i = 0;i < str.length;i ++)
            str[i] = new StringBuffer();
        for(int i = 0;i < s.length();i ++){

            str[j].append(s.charAt(i));
            if(j == 0) 
                down = true;
            else if(j == numRows - 1)
                down =false;
            if(down)
                j ++;
            else
                j --;
        }
        StringBuffer newStr= new StringBuffer();
        for(StringBuffer string : str)
            newStr.append(string.toString());

        return newStr.toString();
    }

你可能感兴趣的:(算法,java,LeetCode解题报告,LeetCode,解题报告)