2

我正在创建一个标记布尔逻辑表达式并返回标记字符串数组的程序。以下是我的代码:

public static String[] tokenize(String s)
{
    String delims = "+";
    StringTokenizer st = new StringTokenizer(s, delims);
    String[] tokens = new String[st.countTokens()];

    int i=0;
    while (st.hasMoreElements()) {
        tokens[i++] = st.nextElement().toString();
    }

    return tokens;
}

例如,我有以下字符串作为输入:

A+B+(C+D+(A+B))+(B+C)

使用我拥有的代码,它只会生成以下令牌:

A
B
(C
D
(A
B))
(B
C)

是否有可能(使用相同的代码结构)提出这些标记?如果不是,它是如何编码的?

A
B
(C+D+(A+B))
(B+C)
4

2 回答 2

0

如果你能找到一个简单的解决方案,那就试试我的

    String s = "A+B+(C+D+(A+B))+(B+C)";
    List<String> l = new ArrayList<>();
    StringBuilder sb = new StringBuilder();
    int p = 0;
    for (char c : s.toCharArray()) {
        if (c == '(') {
            p++;
            sb.append(c);
        } else if (c == ')') {
            p--;
            sb.append(c);
        } else if (p == 0 && c == '+') {
            l.add(sb.toString());
            sb.setLength(0);
        } else {
            sb.append(c);
        }
    }
    if (sb.length() > 0) {
        l.add(sb.toString());
    }
    System.out.println(l);

输出

[A, B, (C+D+(A+B))]
于 2013-09-25T15:35:52.590 回答
0
    ArrayList<String> tokens = new ArrayList<String>();
    String current = "";
    int counter = 0;
    for(int i = 0 ; i < input.length(); i++)
    {
        char c = input.charAt(i);
        if(counter==0 && c=='+')
        {
            tokens.add(current);
            current = "";
            continue;
        }
        else if(c=='(')
        {
            counter++;
        }
        else if(c==')')
        {
            counter--;
        }
        current += c;
    }
    tokens.add(current);

This is the solution for my comment:

You could just loop through 1 character at a time, when you reach a + while not in a parenthesis, save the characters read up to there, and start a new set. The way to track if you're in a a set of parentheses is with a counter. When you hit a open parenthesis, you increment a counter by 1, when you hit a close parenthesis you decrement the counter by 1. If the counter > 0 then you're in parentheses. Oh, and if counter ever goes negative, the string is invalid, and if counter is not 0 at the end, then the string is also invalid.

You can do the checks on counter and return false or something, to show that it is an invalid string. If you know the string is valid then this works as is. You can get an array from the ArrayList, with tokens.toArray()

于 2013-09-25T15:29:11.947 回答