Google Interview Question
1,071 Interview Reviews |
Back to all Google Interview Questions & Reviews
Interview questions and reviews posted anonymously by interview candidates
Interview Question for Software Engineer at Google:
Helpful Question?
Yes |
No
Inappropriate?
Answers & Comments (5)
public String reverse(String s){
char[] a = s.toCharArray();
int n = a.length, j = n-1;
for (int i=0; i < n/2; i++){
char c = a[i]
a[i] = a[j-i];
a[j-i] = c;
}
return new String(a);
}
Helpful Answer?
Yes |
No
Inappropriate?
a = a+b;
b = a-b;
a = a-b;
Will swap a and b!
To convert this into a C solution, pass char* s with the length and use pointers.
void reverse (string &s) {
int start = 0;
int end = s.length() - 1;
while (start < end) {
s[start] = s[start] + s[end];
s[end] = s[start] - s[end];
s[start] = s[start] - s[end];
start++;
end--;
}
}
Helpful Answer?
Yes |
No
Inappropriate?
Helpful Answer?
Yes |
No
Inappropriate?
a = a+b; // this may cause overflow.
you can use the ending '\0' as a temp for swapping, and restore it to '\0' after the whole loop is done.
Helpful Answer?
Yes |
No
Inappropriate?
Members can
answer or comment on this question
–
Join Now (It's Free) or
Sign In
0 of 0 people found this helpful
by neakor:
public void reverse(final char[] array) {
final int half = array.length/2;
final int last = array.length-1;
for(int i = 0; i < half; i++) {
final int j = last-i;
final char ci = array[i];
final char cj = array[j];
array[i] = cj;
array[j] = ci;
}
}