Friday, August 19, 2011

String Reversal in Java, Efficient way

This is very famous question for the interview to reverse the given String. In fact there are multiple ways to implement this program, but the efficient way is here what I given here. Same thing can me implemented using recursive programming as well.


package com.interview;
public class StringRevarsal {
public static void main(String[] args) {
String reverseThis = "Please Reverse Me";
System.out.println(reverse(reverseThis));
}
static String reverse(String reverseMe) {
char[] charArray = reverseMe.toCharArray();
int endIndex = charArray.length-1;
int startIndex = 0;
while (startIndex < endIndex) {
char temp = charArray[startIndex];
charArray[startIndex] = charArray[endIndex];
charArray[endIndex] = temp;
startIndex++;
endIndex--;
}
return String.valueOf(charArray);
}
}


No comments:

Post a Comment