String Reverse program using Swapping in JAVA with complexity o(n/2)

Java_LOGO

Here i am using swapping for reverse the String so we need to run the loop till strLength/2  i.e with complexity o(n/2). Here is the program:
package returncheck;

import java.util.Scanner;

class Reverse {

public String reverseStr(String orgStr) {
char[] charStr = orgStr.toCharArray();
int len = orgStr.length();
char temp;
for (int i = 0; i < len / 2; i++) {
temp = charStr[i];
charStr[i] = charStr[len - i - 1];
charStr[len - i - 1] = temp;
}
return new String(charStr);
}
}

public class Main {

public static void main(String[] args) {
Reverse rev = new Reverse();
Scanner sc = new Scanner(System.in);
System.out.println("Enter String to be Reverse ");
String orgStr = sc.nextLine();
String revStr = rev.reverseStr(orgStr);
System.out.println(" reverse String is : " + revStr);

}
}

Output:

Download Source Code 
Click here to download complete source code
Share on Google Plus

About JK STACK

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment