标签:
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"
思路:
求规律问题
我的代码:
public class Solution { public String convert(String s, int nRows) { if(s == null || s.length() == 0 || nRows <= 1) return s; int gap = 2*nRows - 2; int len = s.length(); StringBuffer rst = new StringBuffer(); for(int i = 0; i < nRows; i++) { for(int j = i; j < len; j+= gap) { rst.append(s.charAt(j)); if(i != 0 && i != nRows-1 && j+gap-2*i < len) { rst.append(s.charAt(j+gap-2*i)); } } } return rst.toString(); } }
学习之处:
对于这种Zigzag的问题,可以转换成数学问题,该问题中就呈现出两个规律。规律很好总结,自己画一下图就显而易见了。
标签:
原文地址:http://www.cnblogs.com/sunshisonghit/p/4350931.html