使用Stack和HashMap形成良好的字符串

时间:2015-10-15 04:39:17

标签: java

形成良好且形状不良的琴弦的例子是:

1.  “A3{DJE(DG[FF]K)WA65}”      - well formed
2.  “BBB[BM98{WJHG]333}”    - Not well formed
3.  “CBY(DDD(WKLP)BEHOP”    - Not well formed

支持的括号为{},[]和()

这是我想要做的事情,并且由于某种原因它总是返回假。

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

public class WellFormedStringCheck {



    public static boolean isWellFormed(String input){

        if(input == null) return true;

        Stack<Character> stack = new Stack<>();

        Map<Character,Character> map = new HashMap<Character,Character>();

        map.put('{', '}');
        map.put('(', ')');
        map.put('[', ']');



        for(int i = 0 ; i < input.length(); i++){

                char s = input.charAt(i);

                if(s == '[' || s == '{' || s == '(' )
                    stack.push(s);
                if(s == ']' || s == '}' || s == ')'){

                    if(stack.isEmpty()) return false;

                    if(map.get(s) != stack.pop()); return false;


                }

            }

        if(!stack.isEmpty()) return false;

         return true;


    }

    public static void main(String[] args) {

      System.out.println(isWellFormed("A3{DJE(DG[FF]K)WA65}"));

    }

}

有谁能告诉我上述方法有什么问题?

2 个答案:

答案 0 :(得分:2)

你犯了一个愚蠢的错误,你为括号,大括号和括号向后构建了参考图。以下是您最初构建地图的方式:

map.put('{', '}');
map.put('(', ')');
map.put('[', ']');

但是当你的键实际上是开头字符时,你正在查找地图中的关闭括号,括号和括号。这将返回null并导致您的方法返回false

以下是您的方法的完整代码:

public static boolean isWellFormed(String input) {
    if (input == null) return true;

    Stack<Character> stack = new Stack<Character>();
    Map<Character,Character> map = new HashMap<Character,Character>();

    map.put('}', '{');
    map.put(')', '(');
    map.put(']', '[');

    for (int i=0; i < input.length(); i++) {
        char s = input.charAt(i);

        if (s == '[' || s == '{' || s == '(') {
            stack.push(s);
        }
        if (s == ']' || s == '}' || s == ')') {
            if (map.get(s) != stack.pop()) {
                return false;
            }
        }
    }

    if (!stack.isEmpty()) {
        return false;
    }
    else {
        return true;
    }
}

我使用IntelliJ中的这个更改测试了您的代码,它似乎运行没有任何问题。

答案 1 :(得分:1)

虽然你得到了一些答案,但你也可以使用Deque,Set&amp; amp;地图。

import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;

public class Main {

    private static Map<Character, Character> map = new HashMap<>();
    private static Set<Character> brackets = new HashSet<>();

    static {
        map.put('{', '}');
        map.put('(', ')');
        map.put('[', ']');

        for (Map.Entry<Character, Character> entry : map.entrySet()) {
            brackets.add(entry.getKey());
            brackets.add(entry.getValue());
        }
    }

    public static void main(String[] args) {
        for (String exp : new String[] { "A3{DJE(DG[FF]K)WA65}", "BBB[BM98{WJHG]333}", "CBY(DDD(WKLP)BEHOP" })
            System.out.printf("%b\t%s%n", validate(exp), exp);
    }

    private static boolean validate(String exp) {
        boolean valid = true;
        Deque<Character> deque = new LinkedList<Character>();
        for (char c : exp.toCharArray())
            if (brackets.contains(c))
                deque.add(c);
        char l, r;
        while (!deque.isEmpty()) {
            l = deque.removeFirst();
            try {
                r = deque.removeLast();
            } catch (NoSuchElementException e) {
                valid = !valid;
                break;
            }
            if (valid) {
                if (r != map.get(l)) {
                    valid = !valid;
                    break;
                }
            }
        }
        return valid;
    }

}