检查括号嵌套在字符串中

时间:2014-02-14 21:24:43

标签: java algorithm data-structures

我对Codility进行了一次训练挑战,检查字符串中括号的正确嵌套。要检查的括号为{,},(,),[,]。我编写了以下java程序,该程序在O(n)时间和空间中传递,但我感觉我使用的额外空间可以减少。此外,我认为必须有一个数据结构,可以更有效地处理这种情况。使用ArrayList而不是数组可能会有所帮助。我需要的是对我的代码的批评。提前谢谢。

这是我写的代码:

import java.util.HashMap;
class Solution {
    public int solution(String S) {
        char[] stack = new char[S.length()];
        int last = -1;
        HashMap hm = new HashMap();
        hm.put('}', '{');
        hm.put(')', '(');
        hm.put(']', '[');
        for(int i=0; i<S.length(); i++){
            char next = S.charAt(i);
            if(next == '}' || next == '{' || next == ')' || next == '(' ||
            next == ']' || next == '[')
            {
                if(last!=-1 && hm.containsKey(next) && stack[last] == hm.get(next)){
                    last--;
                }
                else{
                    last++;
                    stack[last] = S.charAt(i);
                }
            }
        }
        if(last == -1){
            return 1;
        }
        return 0;
    }
}

6 个答案:

答案 0 :(得分:1)

这是一个带有列表的解决方案:

import java.util.LinkedList;    

class Solution {

    public int solution(String S) {
        LinkedList<Character> stack = new LinkedList<>();

        for (int i = 0; i < S.length(); i++) {
            char c = S.charAt(i);

            if (c == '{' || c == '[' || c == '(') {
                stack.push(c);
            } else {
                if (stack.isEmpty()) {
                    return 0;
                }

                char preceding = stack.pop();

                if (c == ')' && preceding != '(') {
                    return 0;
                }

                if (c == ']' && preceding != '[') {
                    return 0;
                }

                if (c == '}' && preceding != '{') {
                    return 0;
                }

            }
        }

        return stack.isEmpty() ? 1 : 0;
    }
}

答案 1 :(得分:1)

jcode for codility Brackets

function solution(S) {
    var head = 0,
        stack = [],
        s_ln = S.length;
        d = {
            "(" : ")",
            "{" : "}",
            "[" : "]"
        };

    for(var i = 0; i < s_ln; i++) {
        if(d[S[i]]) {

            stack[head++] = S[i]; 

        } else {
            if(d[stack[head-1]] === S[i]) {
                head--;
            } else {
                return 0;    
            }
        }

        if (head < 0) return 0;

    }

    return head === 0 ? 1 : 0;
}

result 100% 100%

答案 2 :(得分:1)

这是我的javascript解决方案,其在正确性和性能方面也得分100/100:

https://codility.com/demo/results/trainingXB4S2W-D3F/

function solution(text) {
    var openBrackets = ['(', '[', '<', '{'];
    var closedBrackets = [')',']','>','}'];
    var requiredClosedBrackets = [];
    var chars = text.split('');
    var result = true;
    for (var i = 0; i < chars.length; i++) {
        for (var j = 0; j < openBrackets.length; j++) {
        if (chars[i] == openBrackets[j]) {
            requiredClosedBrackets.push(closedBrackets[j]);
        } else if (chars[i] == closedBrackets[j]) {
            if (chars[i] != requiredClosedBrackets[requiredClosedBrackets.length - 1]) {
            return 0;
          } else {
            requiredClosedBrackets.pop();
          }
        }
      }
    }

    return (requiredClosedBrackets.length == 0) ? 1 : 0;
}

答案 3 :(得分:0)

Java 100/100

https://codility.com/demo/results/demo97TPVG-CPP/

我包含了一个Stack定义,这就是为什么稍长一点,但解决方案很简单:

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();
          }
      }
}

答案 4 :(得分:0)

不是Java,而是JavaScript,它仍然可以提供一些灵感

function checkBrackets(str) {
  var brackets = { '(': ')', '{': '}', '[': ']' };
  var container = { ')': 1, '}': 1, ']': 1 };
  var passed = true;

  for (var i = 0, len = str.length; i < len; i++) {
    if (brackets[str[i]]) {
      var match = brackets[str[i]];
      container[match] = container[match] ? container[match]+1 : 1;
    } else if (container[str[i]]) {
      container[str[i]]--;
    }
  }

  for (var br in container) {
    if (container[br] !== 1) { return false; }
  }

  return passed;
}

console.log(checkBrackets('(])'));
console.log(checkBrackets('()'));
console.log(checkBrackets('(()'));
console.log(checkBrackets('({[]})'));

答案 5 :(得分:0)

我将在2016年尝试回答这个问题。: - p。 下面的代码通过100/100并且易于理解。

package codility.com;

import java.util.Stack;

/**
 * Created by rattanak on 6/29/2016.
 */
public class Solution_Stack_Queue {
    public static void main(String[] args) {
        String s = "()()";
        System.out.print(perfectNesting(s));
    }

    //Q: https://codility.com/c/run/trainingB4J4DF-UZU
    // S empty : return 1;
    // (()(())()) return 1
    // (() : return 0
    // Use of stack to save chars
    public static int perfectNesting(String s) {

        if (s.length() == 0) return 1;
        if (s.length() % 2 == 1) return 0; //odd
        Stack<Character> st = new Stack<Character>();
        for (int i =0; i < s.length(); i++){
            char ch = (char)s.charAt(i);
            if (ch == '(' || ch == '{' || ch == '[' ){
                st.push(s.charAt(i));
            } else { //found )
                if (st.isEmpty()) return 0;
                if (st.peek() != '('){
                    return 0;
                } else {
                    //remove
                    st.pop();
                }
            }
        }

        if (st.isEmpty()) return 1;

        return 0;
    }
}

结果:https://codility.com/demo/results/training8XUE3W-JTX/

如果您有任何问题,请在下面的评论中告诉我。