Optimal Way to Reverse a String in Java

Solution is efficient and follows the two-pointer approach, which is optimal for in-place reversal of a char[]


 class Main {

    public static void main(String[] args) {

        String s="Hello my name is Vikas";

        System.out.println(reverseString(s));

    }

    public static String reverseString(String s){

        char[] c = s.toCharArray();

        int low=0;

        int high=c.length-1;

        while(low<high)

        {

            char temp=c[low];

            c[low++]=c[high];

            c[high--]=temp;

        }

        return new String(c);

    }

}

Previous Post Next Post