QUESTION:
Alphabets are inside () and the number -9<=0>=9 which is under{} solve the string according to the sample input output
Input (z){-2}oho
Output ZZoho
Input ((X){2}(y){3}(z)){2}
Output xxyyyzxxyyyz
Input ((x){2}){0}
output -(nothing should print)
ANSWER
package Practice;
import java.util.*;
class Expressions {
public static void main(String[] args) {
// TODO Auto-generated method stub
String input,output="",temp="",check="";
Scanner scanner=new Scanner(System.in);
input=scanner.nextLine();
Stack <String> stack=new Stack<String>();
for(int i=0;i<input.length();i++)
{
if(input.charAt(i)=='(') {
stack.push("(");
}
else if(input.charAt(i)>='a'&&input.charAt(i)<='z')
{
check+=input.charAt(i);
if(!stack.empty()&&!stack.peek().equals("("))
{
check=stack.pop()+check;
}
stack.push(check);
check="";
}
else if(input.charAt(i)==')')
{
temp=stack.pop();
while(!stack.peek().equals("("))
{
temp=stack.pop()+temp;
}
stack.pop();
stack.push(temp);
}
else if(input.charAt(i)=='{') {
i++;
temp=stack.pop();
if(input.charAt(i)=='-')
{
temp=temp.toUpperCase();
i++;
}
String temp1=temp;
if((input.charAt(i)-48)==0)
temp="";
for(int j=1;j<input.charAt(i)-48;j++)
{
temp+=temp1;
}
i++;
if(input.charAt(i)=='}') {
stack.push(temp);
}
else
{
stack.push("invalid expression");
break;
}
}
}
temp="";
for(int j=0;j<stack.size();j++)
{
temp+=stack.get(j);
}
System.out.println(temp);
}
}
No comments:
Post a Comment