LeetCode--ZigZag Conversion
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 text, int nRows);
convert("PAYPALISHIRING", 3)
should return "PAHNAPLSIIGYIR"
.
问题描述:
给出一个字符串和一个整数numRows,返回得到的zigzag 序列。
解决方法:
找规律,画出当numRows=3,4,5,6时的样子,然后找规律。
通过观察发现,每行起始位置是有后期规律的,彼此间相差span=numRows + (numRows-2)个字符序列;
在非起始行与末尾行中,每个周期都需要加入一个额外的字符,与本次周期起始字符相差 n = numRows + (numRows-2) - i * 2个字符。
程序如下:
public class Solution { public String convert(String s, int numRows) { if(s.length()<=0 || numRows<=1) return s; String res = ""; int span = numRows + (numRows-2); for(int i=0; i<numRows; i++){ String s1 = new String(); for(int j=i; j<s.length(); j=j+span){ s1 = s1 + s.charAt(j); int span1 = numRows +(numRows-2) -2*i; if(i>0 && i<numRows-1 && j+span1<s.length()){//如果是中间行,需要额外加字符 s1 = s1 + s.charAt(j+span1); } } res = res + s1; } return res; } }