首页 > 代码库 > Codility---Brackets
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
show code in pop-up
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。