
题目:
将字符串 “PAYPALISHIRING” 以Z字形排列成给定的行数,比如3:
P A H N A P L S I I G Y I R
|
之后从左往右,逐行读取字符:”PAHNAPLSIIGYIR”
实现一个将字符串进行指定行数变换的函数:
示例:
输入: s = "PAYPALISHIRING", numRows = 4 输出: "PINALSIGYAHRPI" 解释: P I N A L S I G Y A H R P I
|
思路:
就直接模拟,我是采用每个循环竖到底,在斜上去,直到s被遍历完.
public static String (String s, int numRows) { if (s.length() == 1 || numRows == 1){ return s; } if (s.length() == 0){ return ""; } String array[][] = new String[numRows][s.length()]; StringBuilder sb = new StringBuilder(""); int x = 0, y = 0; int cnt = 0; int maxL = s.length(); while (cnt < maxL) { if (cnt != 0) { x = 1; } while (x < numRows) { if (cnt == maxL) { break; } array[x][y] = String.valueOf(s.charAt(cnt)); x++; cnt++; } x -= 2; y++; while (x >= 0) { if (cnt == maxL) { break; } array[x][y] = String.valueOf(s.charAt(cnt)); x--; y++; cnt++; } } for (int i = 0; i < numRows; i++) { for (int j = 0; j <= y; j++) { if (array[i][j] != null && !array[i][j].equals("")) { sb.append(array[i][j]); } } } return sb.toString(); }
|
近期评论