来自codility的问题描述:
如果满足以下任一条件,则认为由N个字符组成的字符串S已正确嵌套:
S是空的; S的格式为“(U)”或“[U]”或“{U}”,其中U是一个正确嵌套的字符串; S的形式为“VW”,其中V和W是正确嵌套的字符串。 例如,字符串“{[()()]}”已正确嵌套,但“([()()”不是。
写一个函数:
class Solution {public int solution(String S); }
给定一个由N个字符组成的字符串S,如果S正确嵌套则返回1,否则返回0。
例如,给定S =“{[()()]}”,函数应该返回1并且给定S =“([()]”,函数应该返回0,如上所述。
假设:
N是[0..200,000]范围内的整数; 字符串S仅由以下字符组成:“(”,“{”,“[”,“]”,“}”和/或“)”。 复杂度:
预期的最坏情况时间复杂度为O(N); 预期的最坏情况空间复杂度是O(N)(不计算输入参数所需的存储空间)。
我得到87%我似乎无法弄清楚问题。
这是我的代码:
// you can also use imports, for example:
// import java.util.*;
import java.util.Stack;
// you can use System.out.println for debugging purposes, e.g.
// System.out.println("this is a debug message");
class Solution {
public int solution(String s) {
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;
}
}
}
return 1;
}
}
答案 0 :(得分:3)
关闭括号中的第一个条件会检查你的堆栈是否有大小!= 1.我认为这是为了检查你是否有任何剩余的开口括号,这是一个好主意。但是,如果您的最后一个字符不是结束括号/ paren /...//>,您将错过整个检查。
例如,(((
等输入会失败。
一个简单的修复方法是在循环结束后检查替换此条件,表明堆栈确实是空的。
答案 1 :(得分:2)
我在C#中的100%解决方案。
using System;
using System.Collections.Generic;
using System.Linq;
class Solution {
private Dictionary<char,char> closing = new Dictionary<char,char>{{'}','{'},{')','('},{']','['}};
public int solution(string S) {
var stack = new Stack<char>();
foreach(var c in S)
{
if(!closing.Keys.Contains(c))
stack.Push(c);
else if(!stack.Any() || closing[c] != stack.Pop() )
return 0;
}
return !stack.Any() ? 1 : 0;
}
}
答案 2 :(得分:2)
在java中通过了100/100的密码测试。
public static int solution(String S){
Stack<Character> stack = new Stack<Character>();
if(null == S){
return 0;
}else if(S.isEmpty()){
return 1;
}
for (Character C : S.toCharArray()) {
switch (C) {
case ')':
pops(stack, '(');
break;
case '}':
pops(stack, '{');
break;
case ']':
pops(stack, '[');
break;
default:
stack.push(C);
break;
}
}
return stack.isEmpty() ? 1 : 0;
}
private static void pops(Stack<Character> s, Character C){
while(!s.isEmpty() && s.peek() != C){
s.pop();
}
if(!s.isEmpty()){
s.pop();
}else{
s.push(C);
}
}
答案 3 :(得分:1)
我知道这与您的问题没有直接关系。
但是我有一个有效的解决方案,其运行时复杂度为O(N),空间复杂度为O(1)。 该解决方案的可编码性为100/100。
用C ++编写:
int solution(string S) {
int N = S.size();
if(N == 0) return 1;//empty string is properly nested
if(S[0] == ')' || S[0] == ']' || S[0] == '}' ) return 0;// a properly nested string cannot beging with those chars
if(S[N-1] == '(' || S[N-1] == '[' || S[N-1] == '{' ) return 0; // cannot end with those chars
int paren_open = 0;
int brac_open = 0;
int curl_open = 0;
for(int i =0 ; i < N;++i){
if(S[i] == ')' && (paren_open == 0 || S[i-1] == '[' || S[i-1] == '{')) return 0; //expected opening but got closing
if(S[i] == ']' && (brac_open == 0 || S[i-1] == '(' || S[i-1] == '{')) return 0; //same here
if(S[i] == '}' && (curl_open == 0 || S[i-1] == '[' || S[i-1] == '(')) return 0; //same here
if(S[i] == '(') paren_open++;
else if(S[i] == ')') paren_open--;
else if(S[i] == '[') brac_open++;
else if(S[i] == ']') brac_open--;
else if(S[i] == '{') curl_open++;
else if(S[i] == '}') curl_open--;
}
if(paren_open == 0 && brac_open == 0 && curl_open ==0)
return 1;
return 0; }
答案 4 :(得分:1)
class Solution {
public int solution(String S) {
// write your code in Java SE 8
Stack<Character> myStack = new Stack<Character>();
for(Character singleChar : S.toCharArray()){
if((singleChar.equals('(')) || (singleChar.equals('{')) || (singleChar.equals('['))){
myStack.push(singleChar);
}
else{
if(myStack.size() == 0){
System.out.println("Stack size");
return 0;
}
if(singleChar.equals(')')){
if(myStack.peek().equals('('))
myStack.pop();
else
return 0;
}
if(singleChar.equals('}')){
if(myStack.peek().equals('{'))
myStack.pop();
else
return 0;
}
if(singleChar.equals(']')){
if(myStack.peek().equals('['))
myStack.pop();
else
return 0;
}
}
}
if(myStack.size()==0)
return 1;
else
return 0;
}
}
答案 5 :(得分:1)
简短干净的Python解决方案来解决此问题。 100%的一致性
void main()
答案 6 :(得分:1)
找不到任何python脚本...但是就在这里!试图使其尽可能简单。
def solution(S):
# write your code in Python 3.6
arr = []
if len(S) < 1:
return 1
if not isinstance(S, str):
return 0
for i in range(0, len(S)):
# print(S[i])
if startSym(S[i]):
arr.append(value(S[i]))
# print(arr)
elif endSym(S[i]):
if len(arr) > 0 and value(S[i]) == arr[len(arr) - 1]:
# print(S[i])
# print(arr)
del arr[len(arr) - 1]
else:
return 0
else:
return 0
if len(arr) == 0:
return 1
else:
return 0
def startSym(x):
if x == '{' or x == '[' or x == '(':
return True
else:
return False
def endSym(x):
if x == '}' or x == ']' or x == ')':
return True
else:
return False
def value(x):
if x == '{' or x == '}':
return 1
if x == '[' or x == ']':
return 2
if x == '(' or x == ')':
return 3
答案 7 :(得分:1)
我在java中使用以下解决方案获得了100%。时间复杂度为O(N)
class Solution {
public int solution(String S) {
char[] charArray=S.toCharArray();
//This array works as stack
char[] stack=new char[charArray.length];
//currently stack is empty
int stackSize=0;
for(int i=0;i<charArray.length;i++){
//Check start characters and add it to stack
if(charArray[i]=='{' ||charArray[i]=='(' || charArray[i]=='['){
stack[stackSize++]=charArray[i];
}else{
//This section checks for end character.
//End characters with stack being empty confirms not nested
if(stackSize==0){
result=0;
break;
}
//Pop stack
char ch=stack[--stackSize];
//check
if((charArray[i]=='}' && ch=='{') || (charArray[i]==']' && ch=='[') ||(charArray[i]==')' && ch=='(')){
continue;
}else{
//if pop character not matching, confirms non nesting
result=0;
break;
}
}
}
//if stack is not empty indicates non nested, otherwise result
return stackSize==0?result:0;
}
}
答案 8 :(得分:1)
100%简单的JavaScript解决方案
function solution(S) {
S = S.split("");
var stack = [];
for (var i = 0; i < S.length; i++) {
var c = S[i];
if (c == '{' || c == '(' || c == '[')
stack.push(c);
else if (c == '}' || c == ')' || c == ']') {
var t = stack.pop() + c;
if (t != "{}" && t != "()" && t != "[]")
return 0;
}
else
return 0;
}
if (stack.length > 0)
return 0;
return 1;
}
答案 9 :(得分:1)
这是我的C#简单解决方案,100%的正确性和100%的性能。时间复杂度是O(N)。 https://codility.com/demo/results/trainingRVS3SF-DC6/
using System;
using System.Collections.Generic;
class Solution {
public int solution(string S) {
// Return 1 if string size is 0
if(S.Length==0) return 1;
Stack<char> brackets = new Stack<char>();
foreach(char c in S){
if(c=='['||c=='{'||c=='('){
brackets.Push(c);
}
else{
// return 0 if no opening brackets found and
// first bracket is a closing bracket
if(brackets.Count==0) return 0;
if(c==')'){
if(brackets.Peek()=='(') brackets.Pop();
else return 0;
}
if(c=='}'){
if(brackets.Peek()=='{') brackets.Pop();
else return 0;
}
if(c==']'){
if(brackets.Peek()=='[') brackets.Pop();
else return 0;
}
}
}
if(brackets.Count==0) return 1;
return 0;
}
}
答案 10 :(得分:0)
这是python中Codility处100%的解决方案
我添加了很少的解释和步骤,希望对您有帮助...
想法 想法是使用堆栈概念 使用数组[]作为堆栈 继续在堆栈中添加项目,直到找到开括号为止;如果找到关闭方括号,则继续弹出项目。 在每个弹出项目中,选中的弹出项目应与示例中说明的相反方括号匹配,否则不平衡。
操作
4 push 4 pop
{[()()]}
push {
push [
push (
pop )
push (
pop )
pop ]
pop }
gets empty
2 push 1 pop
([)()]
(
[
) - not matching with [ so not balanced
代码-
def solution(S):
stack = []
for bracket in S:
# open bracket found push in to stack, used array as stack append item at top
if bracket == "{" or bracket == "[" or bracket == "(":
stack.append(bracket)
# any closing bracket found and stack is not empty remote item from stack top
elif bracket == "}" and stack:
pop_item = stack.pop()
# check popped item, if it is not similar( ie. opposite or open) as bracket then this S can not be balanced
if pop_item != "{":
return 0
elif bracket == "]" and stack:
pop_item = stack.pop()
if pop_item != "[":
return 0
elif bracket == ")" and stack:
pop_item = stack.pop()
if pop_item != "(":
return 0
# at any point if neither open nor close operation can be performed, stack is not balanced
else:
return 0
print(stack)
# if stack is empty stack, it is balanced ie. all push and pop operation on S is successful¬.
if not stack:
return 1
# S is not balanced
return 0
if __name__ == '__main__':
# result = solution("{[()()]}")
result = solution("([)()]")
print("")
print("Solution " + str(result))
运行测试用例-
['{']
['{', '[']
['{', '[', '(']
['{', '[']
['{', '[', '(']
['{', '[']
['{']
[]
Solution 1
['(']
['(', '[']
Solution 0
答案 11 :(得分:0)
我的 %100 JAVA 解决方案
class Solution {
public int solution(String S) {
Stack<Character> myStack = new Stack<>();
char[] chars = S.toCharArray();
for (int i = 0; i < chars.length; i++) {
char coming = chars[i];
switch(coming){
case '(': case '{': case '[':
myStack.push(coming);
break;
case ')': case '}': case ']':
if(myStack.isEmpty())
return 0;
char popped = myStack.pop();
if(!isValidPair(coming, popped))
return 0;
}
}
if(!myStack.isEmpty())
return 0;
return 1;
}
private boolean isValidPair(char c, char s) {
return ((c == ')' && s == '(') || (c == '}' && s == '{') || (c == ']' && s == '['));
}
}
答案 12 :(得分:0)
我认为这是一个更具可读性的 Java 解决方案,得分为 100%:
https://app.codility.com/demo/results/trainingUY545E-2EQ/
import java.util.Stack;
public class Brackets {
public int solution(String S) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < S.length(); i++) {
if (!process(stack, S.charAt(i))) {
return 0;
}
}
return stack.empty() ? 1 : 0;
}
private boolean process(Stack<Character> stack, char ch) {
Character opener = getOpener(ch);
if (opener == null) {
stack.push(ch);
} else {
if (stack.empty()) {
return false;
}
char top = stack.peek();
if (opener.equals(top)) {
stack.pop();
} else {
return false;
}
}
return true;
}
private Character getOpener(char ch) {
switch (ch) {
case ')':
return '(';
case '}':
return '{';
case ']':
return '[';
default:
return null;
}
}
}
答案 13 :(得分:0)
所以在此之后Leeor的建议是100%的解决方案
// you can also use imports, for example:
// import java.util.*;
import java.util.Stack;
// you can use System.out.println for debugging purposes, e.g.
// System.out.println("this is a debug message");
class Solution {
public int solution(String s) {
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 (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;
}
}
答案 14 :(得分:0)
C++ (100%)
#include <stack>
int solution(string &S) {
// write your code in C++14 (g++ 6.2.0)
auto N = S.size();
stack<char> ST;
for(decltype(N) i{0}; i < N; i++) {
if ((S[i] == '{') || (S[i] == '[') || (S[i] == '(')) {
ST.push(S[i]);
}
else {
if (ST.empty()) {
return false;
}
char top = ST.top();
ST.pop();
if ((S[i] == ')') && (top != '(')) {
return false;
}
if ((S[i] == ']') && (top != '[')) {
return false;
}
if ((S[i] == '}') && (top != '{')) {
return false;
}
}
}
return ST.empty();
}
答案 15 :(得分:0)
具有100%准确性的PHP解决方案
$sa = str_split($S);
if(strlen($S) == 0){
return 1;
}
$count = count($sa);
$res =1;
$opening = ['{'=>'}','('=>')','['=>']'];
$array =['{'=>'}','}'=>'{',')'=>'(','('=>')','['=>']',']'=>'['] ;
$stack = [];
for($i =0;$i<$count;$i++){
if(isset($opening[$sa[$i]])){
array_push($stack,$sa[$i]);
}else{
if(count($stack) == 0){
return 0;
}
$v = array_pop($stack);
if($array[$sa[$i]] !== $v){
return 0;
}
}
}
if (sizeof($stack) != 0) return 0;
return 1;
答案 16 :(得分:0)
迅捷5(100%)
public func solution(_ S : inout String) -> Int {
var stack: [Character] = []
let pairFor: [Character: Character] = ["(":")",
"{":"}",
"[":"]"]
let opening: Set<Character> = ["(","{","["]
let closing: Set<Character> = [")","}","]"]
for char in S {
if opening.contains(char) {
stack.append(char)
} else if closing.contains(char) {
guard stack.isEmpty == false else {
return 0
}
let bracket = stack.removeLast()
if pairFor[bracket] != char {
return 0
}
}
}
return stack.isEmpty ? 1 : 0
}
答案 17 :(得分:0)
这是一个简单的Python解决方案(100%):
# Brackets
def solution(S):
if not S:
return 1
stack = []
brackets = {"(": ")", "{": "}", "[": "]"}
for elem in S:
if elem in brackets:
stack.append(elem)
if elem in brackets.values():
if stack:
if elem == brackets[stack.pop()]:
continue
else:
return 0
else:
return 0
return 0 if stack else 1
答案 18 :(得分:0)
JavaScript 100%解决方案
ValueError: Failed to find data adapter that can handle input: (<class 'list'> containing values of types {"<class 'keras_preprocessing.image.dataframe_iterator.DataFrameIterator'>", "<class 'pandas.core.frame.DataFrame'>"}), <class 'pandas.core.frame.DataFrame'>
答案 19 :(得分:0)
def solution(S):
if len(S) == 0:
return 1
opening = ["(", "{", "["]
closing = [")", "}", "]"]
ls_my_o = []
for s in S:
if s in opening:
ls_my_o.append(s)
elif s in closing:
if len(ls_my_o) < 1:
return 0
ele = ls_my_o.pop()
if opening.index(ele) != closing.index(s):
return 0
if len(ls_my_o) == 0:
return 1
return 0
答案 20 :(得分:0)
代码:06:12:11 UTC,c,final,得分:100.00
int solution(char *S) {
// write your code in C99
int len;
if((len=strlen(S))==0) return 1;
char stuck[len];
char open[]="([{";
char close[]=")]}";
int top=0;
for (int i=0;i<len;i++)
{
if (strchr(open,S[i])!=NULL)
{
stuck[top]=S[i];
top++;
}
else if (strchr(close,S[i])!=NULL)
{
if ((top>0)&&((strchr(open,stuck[top-1])-open)==(strchr(close,S[i])-close)))
top--;
else
return 0;
}
}
if (top==0)
return 1;
return 0;
}
答案 21 :(得分:0)
Ruby 100%
def solution(s)
s.split('').inject([]) do |stack, el|
next stack.push(el) if ['[', '{', '('].include?(el)
current = stack.pop
next stack if (current == '{' && el == '}') ||
(current == '(' && el == ')') ||
(current == '[' && el == ']')
return 0
end.empty? ? 1 : 0
end
答案 22 :(得分:0)
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
class Solution {
public static final int BALANCED = 1;
public static final int UNBALANCED = 0;
public int solution(String S) {
if (S.isEmpty()) return BALANCED;
Stack<Character> stack = new Stack<>(S.length());
NestedValidatorUtil util = new NestedValidatorUtil();
for (char c: S.toCharArray()) {
if (stack.isEmpty()){
if (util.isOpener(c)) {
stack.push(c);
} else {
return UNBALANCED;
}
} else {
if(util.isOpener(c)) {
stack.push(c);
} else if(util.getOpenerForGivenCloser(c) == stack.peek()){
stack.pop();
} else {
return UNBALANCED;
}
}
}
return stack.isEmpty() ? BALANCED : UNBALANCED;
}
public static class NestedValidatorUtil {
private Map<Character, Character> language = new HashMap<Character, Character>(){{
put(')','(');
put(']','[');
put('}','{');
}};
public boolean isOpener(Character c) {
return language.values().contains(c);
}
public Character getOpenerForGivenCloser(Character closer) {
return language.get(closer);
}
}
public static class Stack<T> {
public List<T> stack;
public Stack(int capacity) {
stack = new ArrayList<>(capacity);
}
public void push(T item) {
stack.add(item);
}
public T pop() {
T item = peek();
stack.remove(stack.size() - 1);
return item;
}
public T peek() {
int position = stack.size();
T item = stack.get(position - 1);
return item;
}
public boolean isEmpty() {
return stack.isEmpty();
}
}
}
Here's a link to the code。希望它有所帮助。
答案 23 :(得分:0)
对这些错误最好的选择是坐下来写一些单元测试(JUnit是一个很好的框架)来验证你对算法如何工作的理解。
在这种情况下,由于Trengot已经发现&#34; negative_match&#34;输入为))((
,您至少需要这些测试用例:
))((
:这是你的基础测试,一旦你满足要求,并且可以宣布至少部分胜利。}}{{
:这是一般性错误,还是仅与错误处理特定字符有关?})({
:它与重复的字符有关,还是在混合输入中显示?(}{)
:这是否与在字符串开头有开口令牌相关的边缘情况,或者这种行为是否更普遍地出现?一旦你理解实际做什么,而不是你的大脑告诉你它正在做什么(而你的大脑将对你撒谎),修复它应该相当简单。
答案 24 :(得分:0)
简单的java解决方案,100/100
public int solution(String S) {
Deque<Character> stack = new ArrayDeque<Character>();
for(int i = 0; i < S.length(); i++) {
char c = S.charAt(i);
switch (c) {
case ')':
if (stack.isEmpty() || stack.pop() != '(')
return 0;
break;
case ']':
if (stack.isEmpty() || stack.pop() != '[')
return 0;
break;
case '}':
if(stack.isEmpty() || stack.pop() != '{')
return 0;
break;
default:
stack.push(c);
break;
}
}
return stack.isEmpty() ? 1 : 0;
}
答案 25 :(得分:0)
我在Swift中的解决方案。应该正常工作
public func Brackets(_ S : inout String) -> Int {
var Stack = [Character]()
let matching : [Character:Character] = ["(":")", "[":"]", "{":"}"]
for s in S {
let char = S.removeFirst()
if "({[".contains(char) {
print(char)
Stack.append(char)
}
if( "]})".contains(char)) {
print(char)
let bracket = Stack.removeLast()
if matching[bracket] != char {
return 0
}
}
}
return 1
}
var S1 = "{[()()]}"
var S2 = "([)()]"
print("Brackets: ", Brackets(&S1))
print("Brackets: ", Brackets(&S2))
答案 26 :(得分:0)
function solution(S) {
if (0 === S.length) {
return 1
}
let stack = []
for (let i = 0; i < S.length; i++) {
if ('(' === S[i] || '{' === S[i] || '[' === S[i]) {
stack.push(S[i])
} else {
let couple = [stack.pop(), S[i]].join('')
if ('()' !== couple && '{}' !== couple && '[]' !== couple) {
return 0
}
}
}
if (stack.length) {
return 0
}
return 1
}
答案 27 :(得分:0)
100%Java
public int solution(String S) {
Stack<Character> stack = new Stack<>();
for(int i=0; i<S.length(); i++) {
char c = S.charAt(i);
if (c == '[' || c == '{' || c == '(' || c == 'V') {
stack.push(c);
} else if (c == ']' || c == '}' || c == ')' || c == 'W') {
if (checkBracket(stack, c)) {
stack.pop();
} else {
return 0;
}
} else {
return 0;
}
}
if (stack.empty()) {
return 1;
}
return 0;
}
private boolean checkBracket(Stack<Character> stack, char bracket) {
if (stack.empty()) return false;
char lastStackBracket = stack.peek();
if (lastStackBracket == '{' && bracket == '}') {
return true;
} else if (lastStackBracket == '[' && bracket == ']') {
return true;
} else if (lastStackBracket == '(' && bracket == ')') {
return true;
} else if (lastStackBracket == 'V' && bracket == 'W') {
return true;
}
return false;
}
当然你需要导入java.util:
import java.util.*;
答案 28 :(得分:0)
但我相信我的身材更短,没有遗漏任何东西。 我的解决方案在codility中完成了100%。我使用Map来避免重复。这是我在Java中的解决方案。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Droplet Games - Official Site</title>
<link rel="stylesheet" href="css/styles-index.css">
</head>
<body>
<header>
<h1>DROPLET GAMES</h1>
<ul>
<li><a class="active" href="#home">Home</a></li>
<li><a href="#news">Games</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
</ul>
</header>
</html>
答案 29 :(得分:0)
这里你有我在java中的100%解决方案: https://codility.com/demo/results/training2C7U2E-XM3/
/**
* https://codility.com/demo/results/training2C7U2E-XM3/ 100%
*
* Problem facts:
* 1) A string S consisting of N characters is given
* 2) S is properly nested if:
* -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.
* 3) N is an integer within the range [0..200,000];
* 4) string S consists only of the following characters: "(", "{", "[", "]", "}" and/or ")".
* 5) expected worst-case time complexity is O(N);
* 6) expected worst-case space complexity is O(N)
*
* Solution:
* The idea is to iterate over the string and push opening brackets, then each time a closing bracket appears
* it will be matched with the last opening match stacked, if both are of the same type, then pop that char,
* otherwise return 0.
* If the string S is properly nested the remaining stack will be empty.
*
* There are three cases to analize:
* 1) The stack is empty, push the first char.
* 2) The stack is not empty, peek the last char and it is the opening bracket of current closing bracket, then
* pop the char from the stack.
* 3) The stack is not empty, peek the last char and it isn't the opening bracket of current closing bracket,
* return 0, because the string is malformed.
*
* @param S
* @return 1 if S is properly nested and 0 otherwise.
*/
public static int solution(String S) {
if(S.isEmpty()) return 1; // pay attention to corner case 1
if(S.length()==1) return 0; // and 2
Stack<Character> stack = new Stack<>();
for(int i=0; i<S.length(); i++) {
char current = S.charAt(i);
switch (current) {
case '}':
if (!stack.isEmpty() && stack.peek() == '{') {
stack.pop();
}
else return 0;
break;
case ']':
if (!stack.isEmpty() && stack.peek() == '[') {
stack.pop();
}
else return 0;
break;
case ')':
if (!stack.isEmpty() && stack.peek() == '(') {
stack.pop();
}
else return 0;
break;
default:
stack.push(current);
break;
}
}
return stack.size()==0 ? 1 : 0;
}
答案 30 :(得分:-1)
这里是Java 100%
public int solution(String S) {
// write your code in Java SE 8
List open = Arrays.asList('(', '{', '[');
List close = Arrays.asList(')', '}', ']');
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < S.length(); i++) {
if (open.contains(S.charAt(i))) {
stack.push(S.charAt(i));
} else if (close.contains(S.charAt(i)) && !stack.isEmpty()) {
Character top = stack.peek();
if (open.indexOf(top) == close.indexOf(S.charAt(i))) {
stack.pop();
} else {
return 0;
}
} else {
return 0;
}
}
return stack.isEmpty() ? 1 : 0;
}