Skip to content

Commit e193824

Browse files
committed
feat: 186. Reverse Words in a String II
1 parent d532500 commit e193824

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

create_py_solution.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,6 @@
1212

1313
filePath = os.path.join('./py', folderName, folderName+'.py')
1414
if not os.path.exists(filePath):
15-
with open(filePath, 'w'): pass
15+
with open(filePath, 'w'): pass
16+
17+
os._exit(0)
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
from typing import List
2+
import unittest
3+
4+
class Solution:
5+
def reverseWords(self, s: List[str]) -> None:
6+
"""
7+
Do not return anything, modify s in-place instead.
8+
"""
9+
self.swap(s, 0, len(s)-1)
10+
11+
# reverse word
12+
wordStart = 0
13+
for i in range(len(s)):
14+
if s[i] == " ":
15+
self.swap(s, wordStart, i-1)
16+
wordStart = i+1
17+
elif len(s)-1 == i:
18+
self.swap(s, wordStart, i)
19+
20+
def swap(self, s, start, end) -> None:
21+
while start < end:
22+
s[start], s[end] = s[end], s[start]
23+
start += 1
24+
end -= 1
25+
26+
27+
class TestSolution(unittest.TestCase):
28+
def testReverseWords(self):
29+
sol = Solution()
30+
s = ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
31+
sol.reverseWords(s)
32+
self.assertEqual(s, ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"])
33+
s = ["a"]
34+
sol.reverseWords(s)
35+
self.assertEqual(s, ["a"])
36+
37+
if __name__ == '__main__':
38+
unittest.main()

0 commit comments

Comments
 (0)