Skip to content

Commit 242488d

Browse files
Merge pull request #9 from codewithme-py/feat/zigzag-conversion-0006
problem solution & test 0006
2 parents 0afd0fa + 75a11eb commit 242488d

File tree

3 files changed

+78
-0
lines changed

3 files changed

+78
-0
lines changed

problems_cache.json

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19148,5 +19148,40 @@
1914819148
"Longest Alternating Subarray After Removing At Most One Element",
1914919149
"Hard",
1915019150
"longest-alternating-subarray-after-removing-at-most-one-element"
19151+
],
19152+
"4210": [
19153+
"Median of a Binary Search Tree Level",
19154+
"Medium",
19155+
"median-of-a-binary-search-tree-level"
19156+
],
19157+
"4227": [
19158+
"Find Users with Persistent Behavior Patterns",
19159+
"Hard",
19160+
"find-users-with-persistent-behavior-patterns"
19161+
],
19162+
"4214": [
19163+
"Count Dominant Indices",
19164+
"Easy",
19165+
"count-dominant-indices"
19166+
],
19167+
"4213": [
19168+
"Merge Adjacent Equal Elements",
19169+
"Medium",
19170+
"merge-adjacent-equal-elements"
19171+
],
19172+
"4211": [
19173+
"Count Subarrays With Cost Less Than or Equal to K",
19174+
"Medium",
19175+
"count-subarrays-with-cost-less-than-or-equal-to-k"
19176+
],
19177+
"4202": [
19178+
"Maximum Score Using Exactly K Pairs",
19179+
"Hard",
19180+
"maximum-score-using-exactly-k-pairs"
19181+
],
19182+
"4228": [
19183+
"Delayed Count of Equal Elements",
19184+
"Medium",
19185+
"delayed-count-of-equal-elements"
1915119186
]
1915219187
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution:
2+
def convert(self, s: str, numRows: int) -> str:
3+
"""
4+
Reformat string s in zigzag pattern with numRows rows,
5+
and then read it line by line.
6+
Args:
7+
s: Input string
8+
numRows: Number of rows
9+
Returns:
10+
Reformatted string
11+
Examples:
12+
>>> sol = Solution()
13+
>>> sol.convert("PAYPALISHIRING", 3)
14+
'PAHNAPLSIIGYIR'
15+
>>> sol.convert("PAYPALISHIRING", 4)
16+
'PINALSIGYAHRPI'
17+
>>> sol.convert("A", 1)
18+
'A'
19+
"""
20+
if numRows == 1:
21+
return s
22+
rows = ['' for _ in range(numRows)]
23+
current_row = 0
24+
direction = 1
25+
for i in range(len(s)):
26+
rows[current_row] += s[i]
27+
current_row += direction
28+
if current_row == 0 or current_row == numRows - 1:
29+
direction *= -1
30+
return ''.join(rows)
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import pytest
2+
3+
from solutions.zigzag_conversion_0006 import Solution
4+
5+
6+
@pytest.mark.parametrize('s, num_rows, expected', [
7+
('PAYPALISHIRING', 3, 'PAHNAPLSIIGYIR'),
8+
('PAYPALISHIRING', 4, 'PINALSIGYAHRPI'),
9+
('A', 1, 'A'),
10+
])
11+
def test_solution(s: str, num_rows: int, expected: str) -> None:
12+
sol = Solution()
13+
assert sol.convert(s, num_rows) == expected

0 commit comments

Comments
 (0)