Reverse Words in a String
LeetCode 151 · मध्यम · समाधान, intuition और कदम-दर-कदम वॉकथ्रू
Trim → reverse everything → reverse each word.
मैंने Reverse Words in a String (LeetCode 151) ऐसे हल किया — Two Pointers पैटर्न का एक मध्यम प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और line-by-line debugger।
नीचे का विवरण अंग्रेज़ी में है।
Intuition
Do it the in-place way: clean up the spaces, reverse the whole character list so the words are in the right order, then reverse each word individually so its letters read forwards again.
Approach
- 1
Copy characters skipping leading/trailing spaces and collapsing runs of spaces.
- 2
Reverse the full list.
- 3
Walk word by word, reversing each one back.
- 4
Join into a string.
मैंने कैसे हल किया
Reverse all, then each wordPythonO(n) time · O(n) space
class Solution:
def reverseWords(self, s: str) -> str:
def remove_space(l):
left=0
right=len(l)-1
output = []
while left<=right and s[left]==" ":
left+=1
while left<=right and s[right]==" ":
right-=1
while left<=right:
if s[left]!=" ":
output.append(s[left])
elif output[-1]!=" ":
output.append(s[left])
left+=1
return output
def reverse(l,start,end):
while start<end:
l[start],l[end]=l[end],l[start]
start+=1
end-=1
def reverse_word(l):
n=len(l)
start=0
end=0
while start<len(l):
while end<n and l[end]!=" ":
end+=1
reverse(l,start,end-1)
start=end+1
end+=1
l=remove_space(s)
reverse(l,0,len(l)-1)
reverse_word(l)
return "".join(l)
Reverse Words in a String — अक्सर पूछे जाने वाले प्रश्न
Reverse Words in a String के पीछे intuition क्या है?
Do it the in-place way: clean up the spaces, reverse the whole character list so the words are in the right order, then reverse each word individually so its letters read forwards again.
Reverse Words in a String (LeetCode 151) कैसे हल करें?
1. Copy characters skipping leading/trailing spaces and collapsing runs of spaces. 2. Reverse the full list. 3. Walk word by word, reversing each one back. 4. Join into a string.
Reverse Words in a String की time और space complexity क्या है?
Time: O(n)। Space: O(n) for the character list। (Accepted approach: Reverse all, then each word।)
Reverse Words in a String में आम गलतियाँ क्या हैं?
Collapse repeated spaces between words to a single one.