package org.cmania;
public class ReverseString
{
public static void main(String[] args)
{
String str="abcde"; //String to be reversed
System.out.println("Original String: "+str);
System.out.println("Reversed String: "+reverseString(str));
}
/*
* return reversed String with best performance.
* Best case: O(n/2)- (1/2), when we have odd number of characters in string.
* Average case: O(n/2) , generally when we have even number of characters in string.
* Worst case: O(n/2).
*/
public static String reverseString(String str)
{
char ar[]=str.toCharArray();
char temp;
for(int i=0,j=ar.length-1; i<(ar.length/2); i++,j--){
temp=ar[i];
ar[i]=ar[j];
ar[j]=temp;
}
return new String(ar);
}
}
public class ReverseString
{
public static void main(String[] args)
{
String str="abcde"; //String to be reversed
System.out.println("Original String: "+str);
System.out.println("Reversed String: "+reverseString(str));
}
/*
* return reversed String with best performance.
* Best case: O(n/2)- (1/2), when we have odd number of characters in string.
* Average case: O(n/2) , generally when we have even number of characters in string.
* Worst case: O(n/2).
*/
public static String reverseString(String str)
{
char ar[]=str.toCharArray();
char temp;
for(int i=0,j=ar.length-1; i<(ar.length/2); i++,j--){
temp=ar[i];
ar[i]=ar[j];
ar[j]=temp;
}
return new String(ar);
}
}
No comments:
Post a Comment