Skip to content

Commit

Permalink
add: Z 字形变换
Browse files Browse the repository at this point in the history
  • Loading branch information
yi-ge committed Jun 26, 2022
1 parent f0d557f commit 91edf9d
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@
"mincost",
"nums",
"Paddr",
"PAHNAPLSIIGYIR",
"PAYPALISHIRING",
"PINALSIGYAHRPI",
"powx",
"preorder",
"Prinme",
Expand Down
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -391,6 +391,10 @@ TypeScript / JavaScript 基础算法、数据结构练习,包含 LeetCode 或

- LeetCode 710. 黑名单中的随机数 <https://leetcode.cn/problems/random-pick-with-blacklist/>

- [Z 字形变换](src/array/zigzag-conversion.ts)

- LeetCode 6. Z 字形变换 <https://leetcode.cn/problems/zigzag-conversion/>

##

- [最大矩阵](src/stack/maximal-rectangle.js)
Expand Down
16 changes: 16 additions & 0 deletions src/array/zigzag-conversion.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
export function convert (s: string, numRows: number): string {
if (numRows === 1) return s
const res = new Array(numRows).fill('')

for (let i = 0, len = s.length, isDown = true, row = 0; i < len; i++) {
res[isDown ? row++ : row--] += s[i]

if (row === numRows - 1) {
isDown = false
} else if (row === 0) {
isDown = true
}
}

return res.join('')
}
8 changes: 8 additions & 0 deletions test/array/zigzag-conversion.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { convert } from '../../src/array/zigzag-conversion'

test('Z 字形变换', () => {
expect(convert('PAYPALISHIRING', 3)).toBe('PAHNAPLSIIGYIR')
expect(convert('PAYPALISHIRING', 4)).toBe('PINALSIGYAHRPI')
expect(convert('A', 1)).toBe('A')
expect(convert('AB', 1)).toBe('AB')
})

0 comments on commit 91edf9d

Please sign in to comment.