344. Reverse String
Description of the Problem
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 <= 10^5
s[i]is a printable ascii character.
Solution
Tags: String
Code(Rust)
impl Solution {
pub fn reverse_string(s: &mut Vec<char>) {
let (mut i, mut j) = (0, s.len() - 1);
while( i < j){
let c = s[i];
s[i] = s[j];
s[j] = c;
i+=1; j-=1;
}
}
}
Code(Java)
class Solution {
public void reverseString(char[] s) {
int i = 0; int j = s.length - 1;
while( i < j){
char c = s[i];
s[i] = s[j];
s[j] = c;
i++; j--;
}
}
}
Complexity
- n is the length of the string
Time complexity:
- \( T(n) = O(n/2) \)
Auxiliary Space:
- \( S(n) = O(1) \)