Tuesday, October 27, 2015

Reverse of a string in optimized way

Most of the time we came a cross to reverse of a string in interview and interviewer always say it should be optimized.
There are so many ways to reverse a string one of them is mentioned below.

public class StringReverse {
    
    public static void main(String arg[])
    {
        String string="I AM MIKE MORTAN";
        char[] tempCharArray=string.toCharArray();
        int start,end=0;
        end=tempCharArray.length-1;
        for(start=0;start<end;start++,end--)
        {
            char temp=tempCharArray[start];
            tempCharArray[start]=tempCharArray[end];
            tempCharArray[end]=temp;
        }
        
        System.out.println(new String(tempCharArray));
    }

}


In this way we will reverse the string in half of the iteration of a given string, rather than traversing complete string from start to end.

No comments:

Post a Comment

Spring Boot Config Server and Config Client.

 In Spring cloud config we can externalise our configuration files to some repository like GIT HUT, Amazon S3 etc. Benefit of externalising ...