Amazon Interview Question
Software Engineer / Developerspublic class ReverseStringTest {
public static void main(String[] args) {
String str = "What's going on?";
System.out.println(ReverseString.reverseIt(str));
}
}
class ReverseString {
public static String reverseIt(String source) {
int i, len = source.length();
StringBuffer dest = new StringBuffer(len);
for (i = (len - 1); i >= 0; i--)
dest.append(source.charAt(i));
return dest.toString();
}
}
Dude! I am confused. Why don't you simply use StringBuffer's reverse() method? I think when somebody asks for reversing a string they meant without library functions. They want us to work a bit. Here is the simple one with temporary variable.
{public static String getReverse(String input) {
char c[] = input.toCharArray();
int len = c.length - 1;
if (len <= 0) {
return input;
}
for (int i = 0; i < len / 2; i++) {
char temp = c[len - i];
c[len - i] = c[i];
c[i] = temp;
}
return new String(c);
}}
public static String strRev(String str){
StringBuffer strBuf = new StringBuffer();
for(int i = str.length() - 1 ; i >= 0 ; i--){
strBuf.append(str.charAt(i));
}
return strBuf.toString();
}
public static String strRevRecursive(char[] str, int begin, int end){
if(begin >= end){
return String.valueOf(str);
}else{
char temp = str[begin];
str[begin] = str[end];
str[end] = temp;
return strRevRecursive(str, begin+1, end-1);
}
}
Iterative is better by swapping. No extra space. Recursive, stack is used, but simple.
- Messi April 13, 2010