概述
题目描述:
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));
}
}
运行结果:
最后
以上就是从容奇迹为你收集整理的ZigZag Conversion(java)的全部内容,希望文章能够帮你解决ZigZag Conversion(java)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复