【LeetCode】6. Z 字形变换
题目
将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。比如输入字符串为 "LEETCODEISHIRING" 行数为 3 时,排列如下:
L | C | I | R | ||||
E | T | O | E | S | I | I | G |
E | D | H | N |
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"LCIRETOESIIGEDHN"。
示例 1:
输入: s = "LEETCODEISHIRING", numRows = 3
输出: "LCIRETOESIIGEDHN"
示例 2:
输入: s = "LEETCODEISHIRING", numRows = 4
输出: "LDREOEIIECIHNTSG"
解题
初看这题没什么头绪,只要我们把字母转换数字(字符的位置)就能发现其中规律,下面是一个长度16,4行排列的例子0 | 6 | 12 | ||||
1 | 5 | 7 | 11 | 13 | ||
2 | 4 | 8 | 10 | 14 | ||
3 | 9 | 15 |
题目就能转换为 原来字符串 0 1 2 3 4 5 6 7 8 10 11 12 13 14 15 转换后字符串 0 6 12 1 5 7 11 13 2 4 8 10 14 3 9 15 上面例子两种情况
- 首行和尾行两个数字中间都是空
- 中间行两个数字间有且只有一个数字
public string Convert(string s, int numRows) { if (string.IsNullOrEmpty(s)) return s; if (numRows <= 1) return s; var offset = 2 * numRows - 2; var index = 0; var chars = new Char[s.Length]; for (int i = 0; i < numRows; i++) { var subOffset = offset - 2 * i; for (int k = 0; (i + k) < s.Length; k += offset) { chars[index++] = s[i + k]; if (i == 0 || i == numRows - 1) continue; if (i + k + subOffset < s.Length) chars[index++] = s[i + k + subOffset]; } } return new String(chars); }View Code
LeetCode 提交通过
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/zigzag-conversion/solution/z-zi-xing-bian-huan-by-leetcode/
更多精彩