Problem Description
Elena, now deeply engrossed in her exploration of compiler development, has encountered a fascinating challenge related to her new language, L++.
In this linguistic puzzle, she's dealing with abstract instructions represented by the characters "<" and ">," which serve as a shorthand for generating XML code tags in L++.
The rule she's uncovered is that for an expression to be valid, every "<" symbol must be followed, at some point (though not necessarily immediately), by a corresponding ">" symbol. Additionally, each ">" symbol should correspond to exactly one "<" symbol.
To illustrate, expressions like "<<>>," "<>," and "<><>" are considered valid, while expressions like ">>," and "><><" are not.
Elena needs your help in analyzing a set of expressions provided as input to determine the length of the longest prefix that adheres to these rules. If no valid prefix exists, the output should be 0.
Problem Constraints
1 ≤ The length of a single expression ≤ 106
Input Format
The first argument is the expression.
Output Format
Return the length of the longest valid prefix or 0 if there's no such valid prefix.
Example Input
Input 1:
<<>>
Input 2:
><
Input 3:
<>>>
Example Output
Output 1:
4
Output 2:
0
Output 3:
2
Example Explanation
For Input 1:
The entire expression <<>> is valid. There are two '<' symbols and two '>' symbols, and each '<' symbol corresponds to exactly one '>'. Therefore, the length of the longest valid prefix is 4.
For Input 2:
The expression >< is not valid. There is one '<' symbol, but there is no corresponding '>' symbol. Therefore, the length of the longest valid prefix is 0.
For Input 3:
The expression <>>> is not valid. The longest valid prefix is <> which has a length of 2.
NOTE: You only need to implement the given function. Do not read input, instead use the arguments to the function. Do not print the output, instead return values as specified.
Still have a question? Checkout Sample Codes for more details.