Reverse String
LeetCode 344 · सोपा · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू
Swap s[i] with s[n−1−i] for i < n/2.
मी Reverse String (LeetCode 344) असा सोडवला — Two Pointers पॅटर्नमधील एक सोपा प्रॉब्लेम. खाली: intuition, टप्प्याटप्प्याने approach, माझा accepted Python कोड, animated test cases आणि line-by-line debugger.
खालील विवरण इंग्रजीत आहे.
Intuition
Swap the first and last characters, then the second and second-to-last, and so on until the middle. Each swap fixes two positions.
Approach
- 1
Loop i over the first half.
- 2
Swap s[i] and s[n−i−1].
मी कसा सोडवला
Two-ended swapPythonO(n) time · O(1) space
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
n=len(s)
for i in range(n//2):
s[i],s[n-i-1]=s[n-i-1],s[i]
return s
Reverse String — वारंवार विचारले जाणारे प्रश्न
Reverse String मागील intuition काय आहे?
Swap the first and last characters, then the second and second-to-last, and so on until the middle. Each swap fixes two positions.
Reverse String (LeetCode 344) कसा सोडवावा?
1. Loop i over the first half. 2. Swap s[i] and s[n−i−1].
Reverse String ची time आणि space complexity किती आहे?
Time: O(n). Space: O(1). (Accepted approach: Two-ended swap.)
Reverse String मध्ये सामान्य चुका कोणत्या?
Stop at n // 2 or you'll swap everything back.