Determining if a string is balanced

This problem is about determining if a string is balanced, meaning that every open parenthesis has a corresponding close parenthesis, and vice versa. An example of an input string that would return " true" is "(()())". An example of an input string that would return "false" is "())(".

Problem

Given a string containing only parentheses, write a function to determine if the string is balanced. A string is balanced if every open parenthesis has a corresponding close parenthesis and vice versa.
Example input: "()()"
Example output: True
Example input: "((()))"
Example output: True
Example input: "())("
Example output: False

Solution

This solution is in C++. Our A.I. can create solutions in multiple languages.
by kayakane
#include <iostream>
#include <string>
#include <stack>

using namespace std;

bool isBalanced(string s) {
	stack<char> st;
	for (int i = 0; i < s.length(); i++) {
		if (s[i] == '(') {
			st.push(s[i]);
		}
		else if (s[i] == ')') {
			if (st.empty()) {
				return false;
			}
			else {
				st.pop();
			}
		}
	}
	return st.empty();
}

int main() {
	string s1 = "()()";
	string s2 = "((()))";
	string s3 = "())(";
	cout << isBalanced(s1) << endl;
	cout << isBalanced(s2) << endl;
	cout << isBalanced(s3) << endl; return 0;
}

A.I. Evaluation of the Solution

The candidate's solution is complete and solves the problem. The candidate's approach is to use a stack to keep track of the parentheses. Every time the candidate encounters an open parenthesis, they push it onto the stack. Every time the candidate encounters a close parenthesis, they pop off the top element of the stack. If the stack is ever empty when they encounter a close parenthesis, then they know that the string is not balanced. If the stack is not empty when they reach the end of the string, then they know that the string is not balanced.

Evaluated at: 2022-11-24 08:16:11