This question was asked in an interview that I found interesting.
Here you go.
I know, There are other ways to do it better.
Map<Character, Character> exprssionMap = new HashMap<>();
exprssionMap.put('{', '}');
exprssionMap.put('[', ']');
exprssionMap.put('(', ')');
String inputExpression = "{[({{)}}]}";
int expressionLengh = inputExpression.length();
if (expressionLengh % 2 == 1) {
System.out.println("malformed Expression; Size of the Expression is not even number");
} else {
for (int i = 0; i < expressionLengh / 2; i++) {
if (!exprssionMap.get(inputExpression.charAt(i))
.equals(inputExpression.charAt(expressionLengh - 1 - i))) {
System.out.println(
"Matching expression not found for: " + inputExpression.charAt(i) + "; index:" + i);
}
}
}
Happy Coding.
No comments:
Post a Comment