Difference between revisions of "TADM2E 3.1"
From Algorithm Wiki
(Recovering wiki) |
(Recovering wiki) |
||
Line 1: | Line 1: | ||
You just need to maintain a count, like so: | You just need to maintain a count, like so: | ||
− | + | <pre> | |
public static boolean isBalanced(String str) { | public static boolean isBalanced(String str) { | ||
int count = 0; | int count = 0; | ||
− | for (int i = 0, n = str.length(); i | + | for (int i = 0, n = str.length(); i < n; i++) { |
switch (str.charAt(i)) { | switch (str.charAt(i)) { | ||
case '(': | case '(': | ||
Line 17: | Line 17: | ||
} | } | ||
− | if (count | + | if (count < 0) { |
− | System.out.println( | + | System.out.println("Imbalance at index " + i); |
return false; | return false; | ||
} | } | ||
Line 24: | Line 24: | ||
if (count != 0) { | if (count != 0) { | ||
− | System.out.println( | + | System.out.println("Imbalance at index " + (str.length() - 1)); |
return false; | return false; | ||
} | } | ||
Line 30: | Line 30: | ||
return true; | return true; | ||
} | } | ||
− | + | </pre> | |
Another Approach to use stack in-order to solve this problem; | Another Approach to use stack in-order to solve this problem; | ||
A. Read the string from left to right as CHR | A. Read the string from left to right as CHR | ||
− | B. Keep pushing CHR until CHR is not | + | B. Keep pushing CHR until CHR is not ")" |
− | 1) Pop from stack once CHR == | + | 1) Pop from stack once CHR == ")" |
− | if poped element is NOT | + | if poped element is NOT "(" |
return FAlse | return FAlse | ||
Repeat A | Repeat A |
Revision as of 18:22, 11 September 2014
You just need to maintain a count, like so:
public static boolean isBalanced(String str) { int count = 0; for (int i = 0, n = str.length(); i < n; i++) { switch (str.charAt(i)) { case '(': count++; break; case ')': count--; break; default: throw new IllegalArgumentException(); } if (count < 0) { System.out.println("Imbalance at index " + i); return false; } } if (count != 0) { System.out.println("Imbalance at index " + (str.length() - 1)); return false; } return true; }
Another Approach to use stack in-order to solve this problem;
A. Read the string from left to right as CHR B. Keep pushing CHR until CHR is not ")" 1) Pop from stack once CHR == ")" if poped element is NOT "(" return FAlse Repeat A
--Max 07:18, 16 June 2010 (EDT)