Given two expressions in the form of strings. The task is to compare them and check if they are similar. Expressions consist of lowercase alphabets, '+', '-' and '( )'.
Input:
The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case contains two lines. And each line contains an expression.
The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case contains two lines. And each line contains an expression.
Output
For each test case, print in a new line "YES" if the expressions are similar else print "NO".
For each test case, print in a new line "YES" if the expressions are similar else print "NO".
Constraints:
1<=T<=100
3<=|Expression length|<=100
1<=T<=100
3<=|Expression length|<=100
Example:
Input:
2
-(a+b+c)
-a-b-c
a-b-(c-d)
a-b-c-d
Input:
2
-(a+b+c)
-a-b-c
a-b-(c-d)
a-b-c-d
Output:
YES
NO
YES
NO
//JAVA CODE
import java.util.ArrayList; import java.util.Scanner; public class Main { static boolean isequal(String s1,String s2){ return s1.equals(s2); } static char sign_change(int positive,int negative,int parentheses,char a){ if(negative >0 && parentheses>0){ if(a=='-') return '+'; else return '-'; } else { return a; } } static String remove_parenthesis(String s1){ String s=""; int positive =0;int negative=0;int parentheses=0;int flag=0; for(int i=0;i<s1.length();i++){ if(s1.charAt(i)=='-' && parentheses==0){ negative=1; if(flag==0) s+=s1.charAt(i); flag=1; } else if(s1.charAt(i)=='+' && parentheses==0){ positive=1; if(flag==0) s+=s1.charAt(i); flag=1; } else if(Character.isLetter(s1.charAt(i)) && parentheses==0){ s+=s1.charAt(i); flag=0; negative=0;positive=0; } else if(s1.charAt(i)=='(') parentheses++; else if(s1.charAt(i)==')') parentheses--; else if(parentheses>0 && s1.charAt(i)=='+'){ s+=sign_change(positive,negative,parentheses,s1.charAt(i)); } else if(parentheses>0 && s1.charAt(i)=='-'){ s+=sign_change(positive,negative,parentheses,s1.charAt(i)); } else if(parentheses>0 && Character.isLetter(s1.charAt(i))){ s+=s1.charAt(i); } } return s; } static String checking(String k){ int flag=0; int count=0; String f=""; char[]c= k.toCharArray(); ArrayList<Character> ml= new ArrayList<Character>(); for(int i=0;i<c.length;i++) ml.add(c[i]); for(int i=0;i<ml.size();i++){ if(Character.isLetter(ml.get(i))) { count++; flag++; } else { flag= 0; count++; } if(flag==2){ ml.add(count-1,'+'); count=0; flag=0; } } for(int i=0;i<ml.size();i++) f +=ml.get(i); return f; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s1=sc.next(); String s2=sc.next(); String s3=remove_parenthesis(s1); String s4=checking(s3); if(isequal(s4,s2)) System.out.println("yes"); else System.out.println("no"); } }
Comments
Post a Comment