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
0 comments:
Post a Comment