1+ # Reverse Words in a String
2+ # Problem: Given a string, reverse the order of words.
3+
4+ # ------------------------------------------------
5+ # Solution 1: Two Pointer Swap Method
6+ # ------------------------------------------------
7+
8+ class SolutionSwap :
9+ def reverseWords (self , s : str ) -> str :
10+ # split() removes extra spaces and converts string into list
11+ # Example: " hello world " -> ['hello','world']
12+ n = s .split ()
13+
14+ # initialize two pointers
15+ l = 0
16+ r = len (n ) - 1
17+
18+ # swap words until pointers meet
19+ while l < r :
20+ n [l ], n [r ] = n [r ], n [l ]
21+ l += 1
22+ r -= 1
23+
24+ # convert list back to string
25+ return " " .join (n )
26+
27+
28+ # ------------------------------------------------
29+ # Solution 2: Reverse Traversal Method
30+ # ------------------------------------------------
31+
32+ class SolutionLoop :
33+ def reverseWords (self , s : str ) -> str :
34+ # convert string to list of words
35+ n = s .split ()
36+
37+ # empty string to store result
38+ res = ""
39+
40+ # traverse from last word to first word
41+ for i in range (len (n )- 1 , - 1 , - 1 ):
42+ res += n [i ]
43+
44+ # add space between words
45+ if i != 0 :
46+ res += " "
47+
48+ return res
49+
50+
51+ # ------------------------------------------------
52+ # Example Test
53+ # ------------------------------------------------
54+
55+ s = " hello world "
56+
57+ print ("Swap Method:" , SolutionSwap ().reverseWords (s ))
58+ print ("Loop Method:" , SolutionLoop ().reverseWords (s ))
0 commit comments