gpt4 book ai didi

考虑括号的Java StringTokenizer

转载 作者:行者123 更新时间:2023-11-29 08:58:25 25 4
gpt4 key购买 nike

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

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)

最佳答案

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

这是我评论的解决方案:

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.

您可以对计数器进行检查并返回 false 或其他东西,以表明它是一个无效的字符串。如果您知道该字符串是有效的,那么它可以按原样工作。您可以使用 tokens.toArray()

从 ArrayList 获取数组

关于考虑括号的Java StringTokenizer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19008617/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com