/** * * 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". * */ public class ZigZagConversionImpl implements ZigZagConversion{ @Override public String convert(String s, int nRows) { int len = s.length(); if (len <= 2 || nRows<= 1) return s; StringBuilder builder = new StringBuilder(); int step = 2*nRows - 2; for (int i = 0 ; i < nRows; i++){ for (int j = i ; j < len; j+= step){ builder.append(s.charAt(j)); //首列 if (i != 0 && i != nRows -1 && j + step - 2*i <len){ //非首行尾行需添加斜线上的元素. builder.append(s.charAt(j + step - 2*i)); } } } return builder.toString(); } }
LeeCode刷题之ZigZagConversion JAVA实现
最新推荐文章于 2022-08-13 10:47:53 发布