From 91edf9d592e4c5c3636fa7e14e35dc8e50e90904 Mon Sep 17 00:00:00 2001 From: yi-ge Date: Sun, 26 Jun 2022 21:19:02 +0800 Subject: [PATCH] =?UTF-8?q?add:=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 --- .vscode/settings.json | 3 +++ README.md | 4 ++++ src/array/zigzag-conversion.ts | 16 ++++++++++++++++ test/array/zigzag-conversion.test.ts | 8 ++++++++ 4 files changed, 31 insertions(+) create mode 100644 src/array/zigzag-conversion.ts create mode 100644 test/array/zigzag-conversion.test.ts diff --git a/.vscode/settings.json b/.vscode/settings.json index 1f9c99f..9a0129a 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -23,6 +23,9 @@ "mincost", "nums", "Paddr", + "PAHNAPLSIIGYIR", + "PAYPALISHIRING", + "PINALSIGYAHRPI", "powx", "preorder", "Prinme", diff --git a/README.md b/README.md index a17371a..23c1c7a 100644 --- a/README.md +++ b/README.md @@ -391,6 +391,10 @@ TypeScript / JavaScript 基础算法、数据结构练习,包含 LeetCode 或 - LeetCode 710. 黑名单中的随机数 +- [Z 字形变换](src/array/zigzag-conversion.ts) + + - LeetCode 6. Z 字形变换 + ## 栈 - [最大矩阵](src/stack/maximal-rectangle.js) diff --git a/src/array/zigzag-conversion.ts b/src/array/zigzag-conversion.ts new file mode 100644 index 0000000..4dbd705 --- /dev/null +++ b/src/array/zigzag-conversion.ts @@ -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('') +} \ No newline at end of file diff --git a/test/array/zigzag-conversion.test.ts b/test/array/zigzag-conversion.test.ts new file mode 100644 index 0000000..856dda9 --- /dev/null +++ b/test/array/zigzag-conversion.test.ts @@ -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') +}) \ No newline at end of file