Could someone please tell me why code 1 is giving correct output while code 2 is giving WA. Why is the logic in the last if statement in code 1 is mandatory?
Link to questions - CodeChef: Practical coding for everyone
code 1
while(test-->0)
{
String pattern = br.readLine();
long res = 0, count = 0;
Stack<Character> st = new Stack<Character>();
for(int i=0; i<pattern.length(); i++)
{
char c = pattern.charAt(i);
if(st.isEmpty() && c=='>')
break;
if(c=='<')
{
st.push(c);
count++;
}
if(c=='>')
{
count++;
st.pop();
}
if(st.isEmpty())
{
res += count;
count = 0;
}
}
System.out.println(res);
}
code 2
while(test-->0)
{
String pattern = br.readLine();
long res = 0, count = 0;
Stack<Character> st = new Stack<Character>();
for(int i=0; i<pattern.length(); i++)
{
char c = pattern.charAt(i);
if(st.isEmpty() && c=='>')
break;
if(c=='<')
{
st.push(c);
count++;
}
if(c=='>')
{
count++;
st.pop();
}
}
System.out.println(count);
}