Codility---Brackets
Posted Hugh
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Codility---Brackets相关的知识,希望对你有一定的参考价值。
Task description
A string S consisting of N characters is considered to be properly nestedif 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:
class Solution { public int solution(String S); }
that, given a string S consisting of N characters, returns 1 if S is properly nested and 0 otherwise.
For example, given S = "{[()()]}", the function should return 1 and given S = "([)()]", the function should return 0, as explained above.
Assume that:
- N is an integer within the range [0..200,000];
- string S consists only of the following characters: "(", "{", "[", "]", "}" and/or ")".
Complexity:
- expected worst-case time complexity is O(N);
- expected worst-case space complexity is O(N) (not counting the storage required for input arguments).
Solution
Programming language used: Java
Total time used: 14 minutes
Code: 16:26:24 UTC, java, final, score: 100
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
// you can also use imports, for example:
// import java.util.*;
// you can write to stdout for debugging purposes, e.g.
// System.out.println("this is a debug message");
import java.util.Stack;
class Solution {
public int solution(String S) {
// write your code in Java SE 8
if (S.length() % 2 != 0) {
return 0;
}
Character openingBrace = new Character(‘{‘);
Character openingBracket = new Character(‘[‘);
Character openingParen = new Character(‘(‘);
Stack<Character> openingStack = new Stack<Character>();
for (int i = 0; i < S.length(); i++) {
char c = S.charAt(i);
if (c == openingBrace || c == openingBracket || c == openingParen) {
openingStack.push(c);
} else {
if (i == S.length()-1 && openingStack.size() != 1) {
return 0;
}
if (openingStack.isEmpty()) {
return 0;
}
Character openingCharacter = openingStack.pop();
switch (c) {
case ‘}‘:
if (!openingCharacter.equals(openingBrace)) {
return 0;
}
break;
case ‘]‘:
if (!openingCharacter.equals(openingBracket)) {
return 0;
}
break;
case ‘)‘:
if (!openingCharacter.equals(openingParen)) {
return 0;
}
break;
default:
break;
}
}
}
if (! openingStack.isEmpty()) {
return 0;
}
return 1;
}
}
https://codility.com/demo/results/training87ME5J-MVG/
以上是关于Codility---Brackets的主要内容,如果未能解决你的问题,请参考以下文章