Solution to Brackets by codility | Code Says
https://github.com/acprimer/Codility/blob/master/src/Lesson5/Brackets.java
Use linkedlist as stack, stack in java is deprecated
public int solution(String S) {
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < S.length(); i++) {
switch (S.charAt(i)) {
case '(':
case '[':
case '{':
stack.push(S.charAt(i));
break;
case ')':
if (stack.isEmpty() || stack.peek() != '(') return 0;
else stack.pop();
break;
case ']':
if (stack.isEmpty() || stack.peek() != '[') return 0;
else stack.pop();
break;
case '}':
if (stack.isEmpty() || stack.peek() != '{') return 0;
else stack.pop();
break;
}
}
return stack.isEmpty() ? 1 : 0;
}
http://www.martinkysel.com/codility-brackets-solution/
http://codility-lessons.blogspot.com/2015/02/lesson-5-brackets.html
https://github.com/yiqin/Codility-Practice/blob/master/Brackets.java
Read full article from Solution to Brackets by codility | Code Says
A string S consisting of N characters is considered to be properly nested if any of the following conditions is true:
- S is empty;
- S has the form "(U)" or "[U]" or "{U}" where U is a properly nested string;
- S has the form "VW" where V and W are properly nested strings.
For example, the string "{[()()]}" is properly nested but "([)()]" is not.
Write a function:
int solution(char *S);
that, given a string S consisting of N characters, returns 1 if S is properly nested and 0 otherwise.
// use hashsetI’m surprised so few people didn’t do a simple modulo at the start to check whether there is an even number of chars. In production, you wouldn’t want this algorithm to run against a big string and only terminate at the end when one closing token is missing. You’d want it to terminate as soon as it’s possible
def solution(S):
matched = {"]":"[", "}":"{", ")": "("}
to_push = ["[", "{", "("]
stack = []
for element in S:
if element in to_push:
stack.append(element)
else:
if len(stack) == 0:
return 0
elif matched[element] != stack.pop():
return 0
if len(stack) == 0:
return 1
else:
return 0
https://github.com/acprimer/Codility/blob/master/src/Lesson5/Brackets.java
Use linkedlist as stack, stack in java is deprecated
public int solution(String S) {
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < S.length(); i++) {
switch (S.charAt(i)) {
case '(':
case '[':
case '{':
stack.push(S.charAt(i));
break;
case ')':
if (stack.isEmpty() || stack.peek() != '(') return 0;
else stack.pop();
break;
case ']':
if (stack.isEmpty() || stack.peek() != '[') return 0;
else stack.pop();
break;
case '}':
if (stack.isEmpty() || stack.peek() != '{') return 0;
else stack.pop();
break;
}
}
return stack.isEmpty() ? 1 : 0;
}
http://www.martinkysel.com/codility-brackets-solution/
http://codility-lessons.blogspot.com/2015/02/lesson-5-brackets.html
https://github.com/yiqin/Codility-Practice/blob/master/Brackets.java
Read full article from Solution to Brackets by codility | Code Says