344. Reverse String
EasyView on LeetCode
Time: O(n)
Space: O(n)
Advertisement
Intuition
Two-pointer swap: left starts at 0, right at n-1. Swap and move both inward until they meet.
Algorithm
- 1lo=0, hi=n-1. While lo < hi: swap(s[lo], s[hi]); lo++; hi--.
Example Walkthrough
Input: ["h","e","l","l","o"]
- 1.Swap h,o -> ["o","e","l","l","h"]. Swap e,l -> ["o","l","l","e","h"].
Output: ["o","l","l","e","h"]
Common Pitfalls
- •In-place modification - no extra array needed.
344.cs
C#
// Approach: Recursive two-pointer swap: exchange the outermost characters
// then recurse on the inner subarray.
// Time: O(n) Space: O(n)
public class Solution
{
public void ReverseString(char[] s)
{
Reverse(0, s.Length - 1, s);
}
private void Reverse(int l, int r, char[] s)
{
if (l > r)
return;
char temp = s[l];
s[l] = s[r];
s[r] = temp;
Reverse(l + 1, r - 1, s);
}
}344.go
Go
func reverseString(s []byte) {
l := 0
r := len(s) - 1
for l <= r {
temp := s[l]
s[l] = s[r]
s[r] = temp
l++
r--
}
}Advertisement
Was this solution helpful?