I am reading the Algorithm Design Manual Second Edition and this is from an exercise question. Quoting the question
A common problem for comp
I made it a bit more generic Java
public static boolean isBalanced(String expression)
{
// pairs at the same index
List<Character> openers = Arrays.asList('{', '(', '[');
List<Character> closers = Arrays.asList('}', ')', ']');
char[] exp = expression.toCharArray();
Stack<Character> stack = new Stack<>();
for(Character character: exp){
if (openers.contains(character))
stack.push(character);
if(closers.contains(character)){
if (stack.empty())
return false;
//matching pair should be at the same index
Character opener = stack.pop();
int openerIndex = openers.indexOf(opener);
int closerIndex = closers.indexOf(character);
if (openerIndex != closerIndex)
return false;
}
}
return stack.empty();
}
This should work:
public class Balanced {
public static boolean isbalanced(String input) {
int open = 0;
int close = 0;
for (int i=0; i< input.length();i++) {
switch (input.charAt(i)) {
case '{':
case '(':
case '[':
open++;
break;
case '}':
case ')':
case ']':
close++;
default:
break;
}
}
if (open == close){
return true;
}
else {
return false;
}
}
public static void main(String args[]) {
System.out.println(Balanced.isbalanced("()"));
}
}
Why have a return value and an out parameter that give the same information?
You could return an int: -1 = balanced, otherwise the index of the error.
static public bool CheckForBalancedBracketing(string IncomingString)
{
/*******************************************************************
* The easiest way to check for balanced bracketing is to start *
* counting left to right adding one for each opening bracket, '(' *
* and subtracting 1 for every closing bracket, ')'. At the end *
* the sum total should be zero and at no time should the count *
* fall below zero. *
* *
* Implementation: The bracket counting variable is an unsigned *
* integer and we trap an overflow exception. This happens if the *
* unsigned variable ever goes negative. This allows us to abort *
* at the very first imbalance rather than wasting time checking *
* the rest of the characters in the string. *
* *
* At the end all we have to do is check to see if the count *
* is equal to zero for a "balanced" result. *
* *
*******************************************************************/
const char LeftParenthesis = '(';
const char RightParenthesis = ')';
uint BracketCount = 0;
try
{
checked // Turns on overflow checking.
{
for (int Index = 0; Index < IncomingString.Length; Index++)
{
switch (IncomingString[Index])
{
case LeftParenthesis:
BracketCount++;
continue;
case RightParenthesis:
BracketCount--;
continue;
default:
continue;
} // end of switch()
}
}
}
catch (OverflowException)
{
return false;
}
if (BracketCount == 0)
{
return true;
}
return false;
} // end of CheckForBalancedBracketing()
As TheVillageIdiot said, it's fine. You could also implement it recursively, which might be more elegant, or might not. Finally, you might want to require that matching parentheses contain something valid between them, so as to allow "(a)" but not "()".
int i;
int len;
char popped;
stack<char> st;
string a = "({<<";
len = a.length();
for(i=0;i<len;i++)
{
if(a[i] == '<' || a[i] == '(' || a[i] == '[' || a[i] == '{')
{
st.push(a[i]);
continue;
}
if(a[i] == '>' || a[i] == ')' || a[i] == ']' || a[i] == '}')
{
if(st.empty())
{
cout << "stack is empty, when popped , not balanced" << endl;
return 0;
}
else
{
popped = st.top();
st.pop();
if (!((a[i] == '>' && popped == '<') || (a[i] == ')' && popped == '(') || (a[i] == '}' && popped == '{') || (a[i] == '>' && popped == '<'))) //ok
{
cout << "not balanced on character" + std::string(1,a[i]) << endl;
return 0;
}
}
}
}
if(st.empty())
{
cout << "balanced" << endl;
}
else
{
cout << "not balanced stack not empty" << endl;
}