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.