Algorithm
Problem Name: 344. Reverse String
Write a function that reverses a string. The input string is given as an array of characters s
.
You must do this by modifying the input array in-place with O(1)
extra memory.
Example 1:
Input: s = ["h","e","l","l","o"] Output: ["o","l","l","e","h"]
Example 2:
Input: s = ["H","a","n","n","a","h"] Output: ["h","a","n","n","a","H"]
Constraints:
1 <= s.length <= 105
s[i]
is a printable ascii character.
Code Examples
#1 Code Example with C Programming
Code -
C Programming
char* reverseString(char* s) {
int i = 0;
int j;
char c;
if (!s) return s;
j = strlen(s);
if (j < 2) return s;
j --;
while (i < j) {
c = s[j];
s[j] = s[i];
s[i] = c;
i ++;
j --;
}
return s;
}
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with C++ Programming
Code -
C++ Programming
class Solution {
public:
string reverseString(string s) {
reverse(s.begin(), s.end());
return s;
}
};
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with Java Programming
Code -
Java Programming
class Solution {
public void reverseString(char[] s) {
int start = 0;
int end = s.length - 1;
while (start < end) {
char temp = s[start];
s[start++] = s[end];
s[end--] = temp;
}
}
}
Copy The Code &
Try With Live Editor
Input
Output
#4 Code Example with Javascript Programming
Code -
Javascript Programming
const reverseString = function(s) {
s.reverse()
};
Copy The Code &
Try With Live Editor
Input
Output
#5 Code Example with Python Programming
Code -
Python Programming
class Solution:
def reverseString(self, s: List[str]) -> None:
"""
Do not return anything, modify s in-place instead.
"""
for i in range(len(s) // 2):
s[i], s[-i-1] = s[-i-1], s[i]
Copy The Code &
Try With Live Editor
Input
Output
#6 Code Example with C# Programming
Code -
C# Programming
namespace LeetCode
{
public class _0344_ReverseString
{
public void ReverseString(char[] s)
{
if (s == null || s.Length == 0) return;
int i = 0, j = s.Length - 1;
while (i < j)
{
var temp = s[i];
s[i] = s[j];
s[j] = temp;
i++; j--;
}
}
}
}
Copy The Code &
Try With Live Editor
Input
Output