From 3529f5eb22aaa5eeffac5dc46773f6e55ad3b331 Mon Sep 17 00:00:00 2001 From: Flynn Date: Thu, 1 Feb 2024 09:26:51 +0900 Subject: [PATCH] solution: 0006. Zigzag Conversion --- src/0006/index.ts | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/src/0006/index.ts b/src/0006/index.ts index 452f3e2..a45cc5d 100644 --- a/src/0006/index.ts +++ b/src/0006/index.ts @@ -1,3 +1,26 @@ -function convert(s: string, numRows: number): string {} +function convert(s: string, numRows: number): string { + if (numRows === 1) { + return s; + } + + const rows = new Array(numRows).fill(''); + + let currentRow = 0; + let goingDown = true; + + for (const char of s) { + rows[currentRow] += char; + + if (currentRow === 0) { + goingDown = true; + } else if (currentRow === numRows - 1) { + goingDown = false; + } + + currentRow += goingDown ? 1 : -1; + } + + return rows.join(''); +} export { convert };