From db3cd890704e399a4163a316d7ee1e6b71d02cca Mon Sep 17 00:00:00 2001 From: Wen <409053122@qq.com> Date: Mon, 7 Nov 2022 15:50:31 +0800 Subject: [PATCH] =?UTF-8?q?[6]=20Z=20=E5=AD=97=E5=BD=A2=E5=8F=98=E6=8D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/leecode/6.z-字形变换.java | 41 ++++++++++++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/src/leecode/6.z-字形变换.java b/src/leecode/6.z-字形变换.java index 2a2a8fa..2ee5fdd 100644 --- a/src/leecode/6.z-字形变换.java +++ b/src/leecode/6.z-字形变换.java @@ -7,7 +7,46 @@ package leecode;/* // @lc code=start class Solution { public String convert(String s, int numRows) { - return null; + if (numRows == 0 || numRows == 1) return s; + int structNum = numRows + numRows - 2; + int wholeNum = s.length() / structNum; + int lastNum = s.length() % structNum; + int lastCell = lastNum / numRows + (lastNum / numRows == 0 ? 1 : lastNum % numRows); + int cellRight = wholeNum * (numRows - 1) + lastCell; + char[][] resultStruct = new char[numRows][cellRight]; + int cursor = 1; + int structCount = 0; + int row = 0, cell = 0; + boolean back = false; + char[] chars = s.toCharArray(); + for (char aChar : chars) { + if ((cursor - 1) / structNum > structCount) { + row = 0; + cell ++; + structCount = (cursor - 1) / structNum; + resultStruct[row][cell] = aChar; + row ++; + back = false; + } else if (row < numRows && !back) { + resultStruct[row][cell] = aChar; + row ++; + } else { + if (row == numRows) row --; + back = true; + cell ++; + row --; + resultStruct[row][cell] = aChar; + } + cursor ++; + } + StringBuilder sb = new StringBuilder(); + for (char[] chars1 : resultStruct) { + for (char c : chars1) { + if (c == '\u0000') continue; + sb.append(c); + } + } + return sb.toString(); } } // @lc code=end