题目描述:
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));
}
}
运行结果:

本文介绍了一种将字符串以Z字形模式分布在指定行数上的算法,并通过Java实现。该算法将输入字符串按行读取,转换为Z字形排列,再按行输出。示例展示了不同行数下字符串的转换效果。
&spm=1001.2101.3001.5002&articleId=84890385&d=1&t=3&u=bf0bdd5b53514d2c913fe5b55a4453e5)
343

被折叠的 条评论
为什么被折叠?



