Balancing a string using Stack in Java
Balance a string of parentheses. A balanced string would be something like these:
{}()
[{()}]
({()})
An unbalanced string would be something like these:
{}(
({)}
[[
}{
The code below uses the data structure Stack for determining if a string is balanced.
public class StringBalance { public static final String input[] = new String[]{ "{}()", "[{()}]", "[[", "({()})", "{}(" }; public static boolean isBalanced(String s) { Stackstack = new Stack<>(); int current; for (char c : s.toCharArray()) { if (c == '{' || c == '[' || c == '(') { stack.push((int) c); } if (c == '}' || c == ']' || c == ')') { if (stack.empty()) return false; } if (c == '}') { current = stack.pop(); if ((char) current != '{') return false; } if (c == ']') { current = stack.pop(); if ((char) current != '[') return false; } if (c == ')') { current = stack.pop(); if ((char) current != '(') return false; } } return stack.empty(); } public static void main(String[] args) { for (int i = 0; i < input.length; i++) { System.out.println(input[i] + " " + isBalanced(input[i])); } } }
Search within Codexpedia
Custom Search
Search the entire web
Custom Search
Related Posts