https://github.com/emahtab/balanced-brackets
Balanced Brackets
https://github.com/emahtab/balanced-brackets
balanced-brackets balanced-parentheses problem-solving stack
Last synced: 5 months ago
JSON representation
Balanced Brackets
- Host: GitHub
- URL: https://github.com/emahtab/balanced-brackets
- Owner: eMahtab
- Created: 2019-12-04T12:49:25.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2019-12-04T13:14:49.000Z (over 6 years ago)
- Last Synced: 2025-02-02T03:26:22.680Z (over 1 year ago)
- Topics: balanced-brackets, balanced-parentheses, problem-solving, stack
- Homepage:
- Size: 9.77 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Balanced Brackets (Valid Parentheses)
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if: Open brackets are closed by the same type of brackets and in the correct order.
#### Note that an empty string is also considered valid.
```
Example 1:
Input: "()"
Output: true
Example 2:
Input: "()[]{}"
Output: true
Example 3:
Input: "(]"
Output: false
```
## Implementation
```java
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
public class App {
public static void main(String[] args) {
String s = ")[]}";
System.out.println(isValid(s));
}
public static boolean isValid(String s) {
Stack stack = new Stack();
Map map = new HashMap();
map.put("]", "["); map.put(")", "("); map.put("}", "{");
for(int i = 0; i < s.length(); i++) {
String st = Character.toString(s.charAt(i));
if(!map.containsKey(st)) {
stack.push(st);
} else {
if(stack.isEmpty()) {
return false;
} else {
String peek = stack.peek();
if(peek.equals(map.get(st))) {
stack.pop();
} else {
return false;
}
}
}
}
return stack.isEmpty();
}
}
```