难度:
中等
描述:
将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。 比如输入字符串为 "LEETCODEISHIRING" 行数为 3 时,排列如下:
L C I R
E T O E S I I G
E D H N
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"LCIRETOESIIGEDHN"。 请你实现这个将字符串进行指定行数变换的函数:
string convert(string s, int numRows);
示例
1:
输入: s = "LEETCODEISHIRING", numRows = 3
输出: "LCIRETOESIIGEDHN"
2:
输入: s = "LEETCODEISHIRING", numRows = 4
输出: "LDREOEIIECIHNTSG"
解释:
L D R
E O E I I
E C I H N
T S G
来源:力扣(LeetCode) 链接:leetcode-cn.com/problems/zi… 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
语言:
swift
解析:
这题我找到了一个规律,拿row = 5来举例:
A B C
A A B B C C
A A B B C C
A A B B C C
A B C
对应下标为:
0 8 16
1 7 9 15 17 23
2 6 10 14 18 22
3 5 11 13 19 21
4 12 20
我可以将这个字符串分组,具体分成几组,每组有多少个呢?
每组有offset = numRows + numRows - 2 = numRows * 2 - 2个,分成几组当然就是groupNumber = count / offset + 1,当然记得要排除numRows == 1的情况,这个时候offset为零。找到了对应偏移量和组的数量,我们就可以分别对每行的字母进行拼接了。
每行都需要拼接该组第一排的字符,即下标为groupIndex * offset + row的字符,对于非第一行和最后一行,还要加上Z字形折上去的,对应下标我们根据row,使用下一个group的开头去做减法得到为(groupIndex + 1) * offset - row。然后依次将字符拼接上就好了,记得判断是否越界。
代码如下:
class Solution {
func convert(_ s: String, _ numRows: Int) -> String {
if numRows == 1 {
return s
}
var resultString = ""
let stringArray = Array(s)
let offset = numRows * 2 - 2
let count = stringArray.count
let groupNumber = count / offset + 1
for row in 0...numRows - 1 {
for groupIndex in 0...groupNumber - 1 {
if (groupIndex * offset + row) < count {
resultString = resultString + String(stringArray[groupIndex * offset + row])
}
if row != 0 && row != numRows - 1 {
if (groupIndex + 1) * offset - row < count {
resultString = resultString + String(stringArray[(groupIndex + 1) * offset - row])
}
}
}
}
return resultString
}
}
总结
就是找规律吧,注意边界条件。