/** * 6. Z å形忢 *
* å°ä¸ä¸ªç»å®å符串 s æ ¹æ®ç»å®çè¡æ° numRows ï¼ä»¥ä»ä¸å¾ä¸ãä»å·¦å°å³è¿è¡ Z åå½¢æåã *
* æ¯å¦è¾å ¥å符串为 "PAYPALISHIRING" è¡æ°ä¸º 3 æ¶ï¼æåå¦ä¸ï¼ *
* P A H N * A P L S I I G * Y I R ** ä¹åï¼ä½ çè¾åºéè¦ä»å·¦å¾å³éè¡è¯»åï¼äº§çåºä¸ä¸ªæ°çåç¬¦ä¸²ï¼æ¯å¦ï¼"PAHNAPLSIIGYIR"ã *
* è¯·ä½ å®ç°è¿ä¸ªå°å符串è¿è¡æå®è¡æ°åæ¢ç彿°ï¼ *
* string convert(string s, int numRows); *
*
*
* ç¤ºä¾ 1ï¼ *
* è¾å ¥ï¼s = "PAYPALISHIRING", numRows = 3 * è¾åºï¼"PAHNAPLSIIGYIR" *
* ç¤ºä¾ 2ï¼ *
* è¾å ¥ï¼s = "PAYPALISHIRING", numRows = 4 * è¾åºï¼"PINALSIGYAHRPI" * è§£éï¼ *
* P I N * A L S I G * Y A H R * P I ** ç¤ºä¾ 3ï¼ *
* è¾å ¥ï¼s = "A", numRows = 1 * è¾åºï¼"A" *
*
*
* æç¤ºï¼ *
* 1 <= s.length <= 1000 * s ç±è±æåæ¯ï¼å°åå大åï¼ã',' å '.' ç»æ * 1 <= numRows <= 1000 * å°ä¸ä¸ªç»å®å符串 s æ ¹æ®ç»å®çè¡æ° numRows ï¼ä»¥ä»ä¸å¾ä¸ãä»å·¦å°å³è¿è¡ Z åå½¢æåã *
* æ¥æºï¼åæ£ï¼LeetCodeï¼ * 龿¥ï¼https://leetcode.cn/problems/zigzag-conversion * è使å½é¢æ£ç½ç»ææãåä¸è½¬è½½è¯·èç³»å®æ¹ææï¼éåä¸è½¬è½½è¯·æ³¨æåºå¤ã **/ public class Solution6 { public static void main(String[] args) { class Case { String in; int n; String expected; public Case(String in, int n, String expected) { this.in = in; this.n = n; this.expected = expected; } } Case[] cs = new Case[]{ new Case("PAYPALISHIRING", 3, "PAHNAPLSIIGYIR"), new Case("PAYPALISHIRINGOHWEIOFJINSIODV", 5, "PHWSASIHENIYIROIIOPLIGOJDANFV"), }; Solution6 s = new Solution6(); for (Case c : cs) { String result = s.convert(c.in, c.n); System.out.printf("(%s) in: %s, n: %d, real: %s, expect: %s%n", result.equals(c.expected), c.in, c.n, result, c.expected); } } public String convert(String s, int numRows) { // 0 1 2 3 // 0 2 4 // 1 3 5 // 0 4 8 // 1 3 5 7 9 // 2 6 10 // 0 6 // 1 5 7 // 2 4 8 // 3 9 // 0 8 // 1 7 9 // 2 6 10 // 3 5 11 // 4 12 final int len = s.length(); final StringBuilder sb = new StringBuilder(len); final int[] step = new int[2]; for (int i = 0; i < numRows; i++) { if (i == 0 || i == numRows - 1) { step[0] = Math.max((numRows - 1) * 2, 1); step[1] = step[0]; } else { step[0] = (numRows - 1 - i) * 2; step[1] = (numRows - 1) * 2 - step[0]; } int current = 0; for (int j = i; j < len; j += step[current], current = current ^ 1) { sb.append(s.charAt(j)); } } return sb.toString(); } }