The problem context involves checking whether a given string has balanced parentheses. This is a common problem in programming and computer science, often used to validate the syntax of expressions or code blocks. The parentheses types considered in this problem are round brackets '()', square brackets '[]', and curly braces '{}'.
CodeRankGPT is a tool powered by GPT-4 that quietly assists you during your coding interview, providing the solutions you need.
In real-time and absolutely undetectable 🥷
The solution approach uses a stack data structure. It iterates over the characters in the string. When it encounters an opening parenthesis, it pushes it onto the stack. When it encounters a closing parenthesis, it checks if the stack is not empty and if the top element of the stack matches the closing parenthesis. If it does, it pops the element from the stack and continues. If it doesn't, it returns false, indicating that the parentheses are not balanced. After iterating over all the characters, it checks if the stack is empty. If it is, it means all opening parentheses had matching closing ones, so it returns true. Otherwise, it returns false.
/**
*
*/
package com.javaaid.hackerrank.solutions.languages.java.datastructures;
import java.util.Scanner;
import java.util.Stack;
/**
*
*/
public class JavaStack {
private static boolean matchParenthisis(String str) {
Stack st = new Stack();
char[] ch = str.toCharArray();
for (char c : ch) {
if (c == '{' || c == '[' || c == '(') {
st.push(c);
} else {
if (c == ']' && !st.isEmpty() && st.pop() == '[') {
continue;
} else if (c == '}' && !st.isEmpty() && st.pop() == '{') {
continue;
} else if (c == ')' && !st.isEmpty() && st.pop() == '(') {
continue;
} else {
return false;
}
}
}
return st.isEmpty();
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
String s = in.next();
System.out.println(matchParenthisis(s));
}
in.close();
}
}
If you have a HackerRank coding test coming up, you can use CodeRankGPT to your advantage. It will assist you during your interview and help ensure you get the job.
AI is here now, and other candidates might be using it to get ahead and win the job. 🧐
The form has been successfully submitted.