voidreverseString(char* str)
{
int i, j;
char temp;
i=j=temp=0;
j=strlen(str)-1;
for (i=0; i<j; i++, j--)
{
temp=str[i];
str[i]=str[j];
str[j]=temp;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
classSolution {
publicvoidreverseString(char[] s) {
// Initialize two pointersint left = 0;
int right = s.length- 1;
// Continue swapping while left pointer is less than or equal to right pointerwhile (left < right) {
// Swap the characters at left and right positionschar temp = s[left];
s[left]= s[right];
s[right]= temp;
// Move towards the center left++;
right--;
}
}
}
publicvoidreverse(char[] s) {
int n = s.length- 1;
int n = s.length() - 1;
for (int i = 0; i < n / 2; i++){
char c = reversed[i];
reversed[i]= reversed[n-i-1];
reversed[n-i-1]= c;
}
return String.valueOf(reversed);
}
1
2
3
4
5
6
7
8
9
pubfnreverse_string(s: &mut Vec<char>) {
letmut i =0;
let n = s.len();
while i < n /2 {
s.swap(i, n - i -1);
i +=1;
}
}
publicclassSolution {
publicvoidreverseString(char[] s) {
helper(s, 0, s.length- 1);
}
privatevoidreverseHelper(char[] s, int left, int right) {
if (left >= right) {
return;
}
// Swap the characters at left and rightchar temp = s[left];
s[left]= s[right];
s[right]= temp;
// Recursive call to reverse the inner substring helper(s, left + 1, right - 1);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
defreverse_string(self, s: list) ->None:
self.helper(s, 0, len(s) -1)
def_reverse_helper(self, s: list, left: int, right: int) ->None:
if left >= right:
return# Swap the characters at left and right s[left], s[right] = s[right], s[left]
# Recursive call to reverse the inner substring self.helper(s, left +1, right -1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
pubfnreverse_string(s: &mut Vec<char>) {
Self::reverse(&mut s[..]);
}
fnreverse(s: &mut [char]) {
let len = s.len();
if len <2 {
return;
}
s.swap(0, len -1);
Self::reverse(&mut s[1..len -1]);
}
publicclassSolution {
publicvoidreverseString(char[] s) {
Stack<Character> stack =new Stack<Character>();
// Push all characters of the string onto the stackfor (char c : s) {
stack.push(c);
}
// Pop all characters from the stack and put them back into the stringfor (int i = 0; i < s.length; i++) {
s[i]= stack.pop();
}
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution:
defreverse_string(self, s: list) ->None:
stack = []
# Push all characters of the string onto the stackfor char in s:
stack.append(char)
# Pop all characters from the stack and put them back into the stringfor i in range(len(s)):
s[i] = stack.pop()
1
Space Complexity: O(n) as we are using stack data structure.
Method 5 - Using xor to swap (selective programming language)#