Z字形变换(java)

将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。
输入: s = "LEETCODEISHIRING", numRows = 3
输出: "LCIRETOESIIGEDHN"

public static void zChange(String s,int n) {
	String[] temp=new String[s.length()];
	for(int i=0;i

采用stringbuilder

public static String convert(String s, int numRows) {
	if (s==null||s.length()==0||numRows<=1) {
		return s;
	}
	
	StringBuilder[] array=new StringBuilder[numRows];
	for (int i = 0; i < array.length; i++) {
		array[i]=new StringBuilder();
	}
	
	int dir=1;
	int index=0;
	for(char c:s.toCharArray()) {
		array[index].append(c);
		index+=dir;
		if(index==0||index==numRows-1)dir=-dir;
	}
	StringBuilder result=new StringBuilder();
	
	for (int i = 0; i < array.length; i++) {
		result.append(array[i]);
	}
		
	return result.toString();
}
public static void main(String[] args) {
	System.out.println(convert("LEETCODEISHIRING",3));
}

 

你可能感兴趣的:(算法)