[Interview] Reverse C/C++ Style String
Question:
Write code to reverse a C-Style String. (C-String means that “abcd” is represented as five characters, including the null character.)
Solution:
Time Complexity: \(O(n)\)
Space Complexity: \(O(n)\)
Write code to reverse a C-Style String. (C-String means that “abcd” is represented as five characters, including the null character.)
Solution:
public class Solution{
public String reverse(String str) {
int p1 = 0;
int p2 = str.length() - 1;
char temp;
char[] c = new char[p2];
c = str.toCharArray();
while (p1 < p2) {
temp = c[p1];
c[p1] = c[p2];
c[p2] = temp;
p1++;
p2--;
}
return new String(c);
}
}
Complexity Analysis:Time Complexity: \(O(n)\)
Space Complexity: \(O(n)\)
Comments
Post a Comment