ZigZag Conversion(java)

题目描述:

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

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

And then read line by line: "PAHNAPLSIIGYIR"

Write the code that will take a string and make this conversion given a number of rows:

string convert(string s, int numRows);

Example 1:

Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"

Example 2:

Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:

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

代码:

package zigzag;

import java.util.ArrayList;
import java.util.List;

public class zigzag {
	 public static String convert(String s, int numRows)
	 {
		 //定义一个stringbuild集合
		 List<StringBuilder> adds=new ArrayList<>();
		 //利用循环生成每一个元素都具有StringBuilder的属性
		 for (int i = 0; i < Math.min(s.length(), numRows); i++) {
			adds.add(new StringBuilder());
		}
		 //用于标记运动的行位置
		 int indexRow=0;
		 //用于标记运动方向
		 boolean indexDirection=false;
		 for (char c : s.toCharArray()) {
			adds.get(indexRow).append(c);
			//判断是否在转折处
			if (indexRow==0||indexRow==numRows-1) {
				indexDirection=!indexDirection;
			}
			indexRow+=indexDirection?1:-1;
		}
		 //既然已经生成需要的了,现在只需要取出来即可
		 StringBuilder sb=new StringBuilder();
		 for (StringBuilder sb1 : adds) {
			sb.append(sb1);
		}
		 return sb.toString();
	 }
	 public static void main(String[] args) {
		String ss="PAYPALISHIRING";
	    int n=3;
	    int m=4;
		System.out.println(convert(ss, n));
		System.out.println(convert(ss, m));
	}
}

运行结果:

猜你喜欢

转载自blog.csdn.net/zhou_438/article/details/84890385
今日推荐