Reverse String LeetCode JAVA 2 Different Solutions

 public static void main(String arg[]){

Scanner sc=new Scanner(System.in);

System.out.println("Enter total number of characters in string");

int n=sc.nextInt();

char arr[]=new char[n];

for(int i=0;i<n;i++){

arr[i]=sc.next().charAt(0); ;

}

for(int i=0;i<n;i++){

System.out.print(arr[i]+" ");

}

/*

Approach 1 :

Swapping elements till half.

Leetcode stats: Runtime 112 seconds, Memory 42.4 MB. 

int start=0;

int end=arr.length-1;

while(start<end){

char temp;

temp=arr[start];

arr[start]=arr[end];

arr[end]=temp;

start++;

end--;

}

for(int i=0;i<n;i++){

System.out.print(arr[i]+" ");

}

*/

//============================================================

/*

Approach 2 :

Using the StringBuffer reverse method.

Leetcode stats: Runtime 114 seconds, Memory 41.8 MB. 

String str = new String(arr);

StringBuffer sb=new StringBuffer(str);

str=(sb.reverse()).toString();

//arr=str.toCharArray();  

//(you can use this direct method also but in leetcode they will not accept the direct                                //conversion so we have to iterate the string and then store characters in the array.)

for(int i=0;i<str.length();i++){

arr[i]=str.charAt(i);

}

for(int i=0;i<arr.length;i++){  

System.out.print(arr[i]+" ");  

}

*/

}




Thanks for reading.
Hope you liked it.
Please like and comment.
Feel free to ask any doubt.😇

Comments

Popular posts from this blog

Solutions Of Practice Questions Dated 01-06-2022

CODEFORCES SPY DETECTED ROUND 713

Maximum Winning Score Geeks For Geeks