题目描述:
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)
复制代码
1
2
3P 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:
复制代码
1string convert(string s, int numRows);
Example 1:
复制代码
1
2Input: s = "PAYPALISHIRING", numRows = 3 Output: "PAHNAPLSIIGYIR"
Example 2:
复制代码
1
2
3
4
5
6
7
8Input: s = "PAYPALISHIRING", numRows = 4 Output: "PINALSIGYAHRPI" Explanation: P I N A L S I G Y A H R P I
代码:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42package 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)); } }
运行结果:
最后
以上就是从容奇迹最近收集整理的关于ZigZag Conversion(java)的全部内容,更多相关ZigZag内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复