编辑
ZigZag Conversion
本文访问次数:0
  1. 1. 问题链接
  2. 2. 问题描述
  3. 3. 解决方法

问题链接

ZigZag Conversion | LeetCode OJ

问题描述

给出行数,将字符串PAYPALISHIRING用曲折的方式写出来,例如行数为3,该字符串应该写作:

P   A   H   N
A P L S I I G
Y   I   R

然后逐行读出来为PAHNAPLSIIGYIR

解决方法

public class Solution {
    public String convert(String s, int numRows) {
         if(numRows == 1){
            return s;
        }
        
        String result = "";
        
        for(int row = 0; row < numRows; row ++ ){
            int step = 1;
            int bottomStep = 1;
            int upStep = 1;
            if(row == 0||(row == numRows - 1)){
                step = 2*numRows - 2;
                upStep = step;
                bottomStep = step;
            }
            else{
                bottomStep = (numRows-row-1)*2;
                upStep = row*2;
                step = upStep;
            }
            for(int position = row;position < s.length();position+=step){
                
                result += s.substring(position,position+1);
                if(step != upStep){
                    step = upStep;
                }
                else if(step != bottomStep){
                    step = bottomStep;
                }
            }
        }
        return result;
    }
}

需要输入验证码才能留言

没有任何评论