Wednesday, 6 January 2016

Reverse String - keeping performance in mind (without StringBuffer) in java

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);
 }
}

No comments:

Post a Comment

JSP interview questions and answers

Q1. What is JSP and why do we need it? JSP stands for JavaServer Pages. JSP is java server side technology to create dynamic web pages. J...