题目描述:
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:
解题思路:
这道题中每行出现的字母的位置是有规律的,以从第1行到第numRows行,再到第2行为一次循环,除了从第1行与第numRows行有1个字母出现外,其余各行都有2个字母出现,而且这两个字母的位置与所在行数有关。各次循环之间的间隔是一样的,所以把握此规律逐行读入所在位置的字母即可。读入时要保证计算出的位置小于字符串的长度。
具体代码:
public class Solution { public static String convert(String s, int numRows) { //如果numrows为1或者字符串长度小于numRows,则直接返回字符串即可 if(numRows==1) return s; if(s.length()<=numRows) return s; StringBuilder sb =new StringBuilder();//保存读入的字符 int len = s.length(); for(int i=0;i<numRows;i++){ if(i==0){ int num=0; while(num<len){ sb.append(s.charAt(num)); num=num+2*(numRows-1); } } else if(i==numRows-1){ int num=i; while(num<len){ sb.append(s.charAt(num)); num=num+2*(numRows-1); } } else{ int num1=i; int num2=i+2*(numRows-1-i); while(num1<len){ sb.append(s.charAt(num1)); if(num2<len) sb.append(s.charAt(num2)); num1=num1+2*(numRows-1); num2=num2+2*(numRows-1); } } } return sb.toString(); } }