VariableDeclaration
TCCC05 Semi 3 · 2005-01-10 · by Yarin
Problem Statement
Structured langugages such as Java, C# and C++ are made up of blocks of code (usually nested several levels), where the start and end markers for a block are denoted by curly brackets, '{' and '}'. A variable declared in a block is only accessible within that block and its sub-blocks.
In C#, you are not allowed to declare a variable in a block if any of its sub-blocks also declares a variable with the same name. The following code, for instance, will give a compiler error in C# (but not in Java or C++):
public void MyMethod()
{
for(int j = 0; j < 5; j++)
{
int i = j;
}
int i = 0;
}
Changing int i = 0; to { int i = 0; } would be legal C#.
Your task is to write a method which finds this kind of illegal variable declaration. The input will be a
Create a class VariableDeclaration containing the method badVariable which takes a
Constraints
- code will contain between 2 and 50 characters, inclusive.
- Each character in code will be a '{', a '}' or a lowercase letter.
- The curly brackets in code will match up properly.
- Tbere will be a single outer block; that is, the first character in code will be a '{', whose corresponding '}' will be the last character.
- A variable won't be declared more than once in the same block.
"{{ji}i}"
Returns: "i"
This is the example in the problem statement.
"{{ji}{i}}"
Returns: ""
"{d{{e}{fd}}{e}{df{{a}}}a}"
Returns: "ad"
Make sure not to output duplicates, and to sort the badly declared variables in alphabetical order.
"{a{{{{{{{{{{{{{{{{{{{{{{{a}}}}}}}}}}}}}}}}}}}}}}}}"
Returns: "a"
"{{{{{{{{{{{{{{{{{{{{{{{{z}}}}}}}}}}}}}}}}}}}}}}}z}"
Returns: "z"
Submissions are judged against all 59 archived test cases, of which 5 are shown here. Case numbers match the judge’s.
Language: C++17 · define a public class VariableDeclaration with a public method string badDeclaration(string code) · 59 test cases · 2 s / 256 MB per case