Open Close Curly Braces Verification (QA Technical InterviewAssignment — Algorithm / Java)
The task given during the interview was to implement an algorithm/method to return the given boolean outputs based on the open-closed state of the curly braces within the string. Despite the pattern, all the opened curly braces must have closing curly braces.
Expectation:
1. "{}" -> return true;
2. "}{" -> return false;
3. "{}{}{}" -> return true;
4. "{{}{}}}" -> return false;
5. "}{}{}{" -> return false;
6. "{{}{}}" -> return true;
7. "{{}{}}}{" -> return false;
8. "}}}}}}{{" -> return false;
Since each curly brace must have closure, the character count must remain in evens always. Therefore the strings with odd character counts can be eliminated without further verifications. Then, for the string with even character counts, further verifications are to be proceeded with as below.
Test Method (TestNG Annotated)
@Test
public void bracesCompare() {
List<String> list = new ArrayList<String>();
list.add("{}");
list.add("}{");
list.add("{}{}{}");
list.add("{{}{}}}"); // odd character count input
list.add("}{}{}{");
list.add("{{}{}}");
list.add("{{}{}}}{");
list.add("}}}}}}{{");
for (String listItem : list) {
System.out.println(list.indexOf(listItem) + 1 + " - " + listItem + " is " + isOpenBracesClosed(listItem));
}
}
Function Method
public boolean isOpenBracesClosed(String strPattern) {
int strLength = strPattern.length();
if (strLength % 2 == 1) {
return false;
}
else{
int j = 0;
int openCloseBracesDiff = 0;
boolean flagState = true;
for (int i = 0; i < strLength; i++) {
if (strPattern.charAt(i) == '{')
openCloseBracesDiff = openCloseBracesDiff + 1;
else
openCloseBracesDiff = openCloseBracesDiff - 1;
if (openCloseBracesDiff == 0)
{
if (compareNestedPair(strPattern.charAt(j), strPattern.charAt(i),'{','}')) {
return false;
}
if (j + 1 < i) {
flagState = isOpenBracesClosed(strPattern.substring(j + 1, i));
}
j = i + 1;
}
}
if (openCloseBracesDiff == 0)
return flagState;
return false;
}
}
private boolean compareNestedPair(char indexOneActual, char indexTwoActual, char indexOneExpected, char indexTwoExpected) {
if (indexOneActual == indexOneExpected) {
if (indexTwoActual == indexTwoExpected)
return false;
return true;
}
return true;
}
Hope this will be helpful. Feel free to leave your feedback and comments, which can lead us to a friendly discussion below.