Google Interview Question

* Write a function, preferably in C or C++, to reverse a string.

Interview Answers

Anonymous

Nov 28, 2009

Thanks all for the nice solutions. There's another good C solution at StackOverflow, and it's allegedly UTF safe: http://stackoverflow.com/questions/198199/how-do-you-reverse-a-string-in-place-in-c-or-c/198264#198264

1

Anonymous

Feb 18, 2010

@ vic 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.

Anonymous

Nov 9, 2009

I'm no c/c++ person. so here's my solution in java. 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; } }

Anonymous

Nov 10, 2009

More concisely (still Java): 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); }

Anonymous

Nov 27, 2009

C++ Solution. I got this question on another interview albeit with the constraint that I couldn't use any temp variables. So the swapping is done using math: 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--; } }