ZigZag-LeetCode题目解析(java实现)

本文深入解析了LeetCode上的ZigZag算法题,详细介绍了如何使用Java实现字符串的Z字形排列转换,通过具体代码示例展示了算法的运行过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ZigZag-LeetCode题目解析(java实现)

题目描述
在这里插入图片黑色字符相差row,row等于2*numRows - 2,红色字符j +row -i(i指的是当前行数,j指的是前一字符的列数)


package Leet_Code;

public class ZigZag {
	    public String convert(String s, int numRows) {
	    	StringBuilder res = new StringBuilder();
	    	if(numRows == 1) return res.toString();
	        int row = 2*numRows - 2;
	        int n = s.length();
	        for(int i=0;i<numRows;++i){
	            for(int j=i;j<n;j+=row){
	                res.append(s.charAt(j));
	                System.out.println("res:"+res);
	                System.out.println("i:"+i);
	                System.out.println("j:"+j);
	                int tmp = j +row -i;
	                if(i!=0&&i!=numRows-1&&tmp<n)
	                    res.append(s.charAt(tmp));
	                System.out.println("res:"+res);
	                System.out.println("i:"+i);
	                System.out.println("j:"+j);
	            }
	        }
	        return res.toString();
	    }
	    public static void main(String[] args){
	    	ZigZag z = new ZigZag();
	    	String s = "PAYPALISHIRING";
	    	int numRows = 3;
	    	String result = new String();
	    	result = z.convert(s,numRows);
	    	System.out.println(result);
	    }
}