Divide and Conquer is a programming technique which makes the program more efficient to write. And this technique work on the concept of recursion to solve a problem step by step. Generally this technique work in three parts:- Divide:- Divide the problem into some subproblem. Conquer:- Conquer the subproblem by calling recursively until subproblem solved. Combine:- (Optional Step) Combine the subproblem solution. So, that we will get the final problem Solution. When the subproblems are large enough to solve recursively, we call the recursive case. Once the subproblem becomes small enough that we no longer recursive, we say that the recursion "bottom out" and that we have gotten down to the base case. Application of Divide and Conquer Quick Sort Strassen's algorithm for matrix multiplication Merge Sort Counting inversions Binary Search Finding Min and ...
Reverse Words
Given a list of space separated words, reverse the order of the words. Each line of text contains L letters and W words. A line will only consist of letters and space characters. There will be exactly one space character between each pair of consecutive words.
Input
The first line of input gives the number of cases, N.
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Rishabh
*/
public class Reversestring {
public static void main(String[] args) {
// TODO code application logic here
int i;
Scanner sc=new Scanner(System.in);
int N=sc.nextInt();
String s=null;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
ArrayList<String> Al=new ArrayList<>();
for( i=0;i<N;i++)
{
s=sc.next();
s+=sc.nextLine();
Stack<String> stk=new Stack<>();
StringTokenizer st=new StringTokenizer(s," ");
while(st.hasMoreTokens())
{
s=st.nextToken();
s=s.trim();
stk.push(s);
}String output = "";
String out = null;
while(!stk.empty())
{ out=(String) stk.pop();
output+=out;
output=output+" ";
}
Al.add(output);
output=null;
}int m=1;for(String a : Al)
{
a=a.trim();
System.out.println("Case #"+m+":"+" "+a);
m++;
}
}
}
Comments
Post a Comment