Amazon interview question

Reverse a string in-place.

Interview Answers

Anonymous

2 Jul 2011

@Rahul, Wouldn't the for condition be i < strlen(str)/2? that way if you had a string of length 5, it would run for i=0 and i=1, but it wouldn't bother doing i=2 since that is the middle element and doesn't need switching. Without the /2, you will reverse it, then re-reverse it again. For an even length (like 6) you'd want it to do swaps on i=0, i=1, and i=2, but not i=3

3

Anonymous

23 Sept 2011

public static String reverseString(String s){ int len = s.length(); int temp = len; StringBuffer sb = new StringBuffer(); try { for(int i=1;i

Anonymous

22 Jan 2012

void reverse(char* str) { int len = strlen(str); char* end = str + len - 1; for(char* start = str; start > end; ++start, --end ) { char ch = *start; *start = *end; *end = ch; } }

Anonymous

27 Jun 2011

for(i = 0; i < strlen(str); i++) { temp = str[i]; str[i] = str[strlen(str) - 1 - i]; str[strlen(str) - 1 - i] = temp; }

1