如何根据顺序是否正确将给定的括号字符串中的字符值转换为整数?

How do i turn values of characters from a given String of parens into Integers depending if their order is correct?

任务是将给定的括号示例字符串:“(())”设置为数字 0,1 和 -1。

如果给定字符串中给定的括号“(”有一对“)”,则数字 0 将是“(”的整数。
如果给定的括号“)”在给定的字符串中有一对“(”,则数字 1 将是“)”的整数。
如果 none 中有一对,或者更准确地说,如果它们在给定字符串中未闭合,则数字 -1 将是“(”或“)”的整数。
例如:

1.Input:      2.Input:      3.Input    ​
(()           ())           ((())(()))))
Output:       Output:       Output:
-101          01-1          0001100111-1-1

我尝试使用堆栈来检查括号的顺序是否正确,但我无法根据条件为它们设置值。

String parens="(())";
        Stack<Character> s = new Stack<>();
        char c;

        for(int i=0;i<parens.length();i++) {
            c=parens.charAt(i);
            if(c=='(')
                s.push(c);
            else if(c==')') {
                if(s.empty() || s.peek()!='(')
                    continue;
                else
                    s.pop();
            }
        }

        if(s.empty()) {
            System.out.println("Correct");
        }else {
            System.out.println("Incorrect");
        }

虽然您的总体想法是正确的 - 它需要进行调整以适应主要任务“将大括号转换为数字”。

让我们采用下一个解决任务的假设:

  • 将使用索引的临时结果字符串数组
  • 将使用用于保存打开(且尚未关闭)大括号的索引的堆栈

下一个算法:

  1. 使用下一个规则迭代给定的字符串:
  • 如果堆栈为空且当前索引处的字符为 ')' - 当前索引为“-1”
  • 如果堆栈为空且当前索引处的字符为“(” - 将当前索引压入堆栈
  • 如果堆栈不为空且当前索引处的字符为 ')' - 将当前索引的结果设置为“1” - 并将弹出索引的设置结果处的堆栈弹出元素(匹配的开大括号索引)为“ 0
  • 如果堆栈不为空且当前索引处的字符为“(” - 将当前索引压入堆栈
  1. 遍历字符串后 - 对于堆栈中的每个元素 - 结果应为“-1”
  2. 将所有结果合并为 1 个字符串

代码:

private static String convert(String input) {
    String[] result = new String[input.length()];

    Stack<Integer> openPositions = new Stack<>();

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

        if (openPositions.isEmpty()) {
            if (currentChar == ')') {
                result[i] = "-1";
            } else {
                openPositions.push(i);
            }
        } else {
            if (currentChar == ')') {
                result[i] = "1";
                result[openPositions.pop()] = "0";
            } else {
                openPositions.push(i);
            }
        }
    }

    openPositions.forEach(index -> result[index] = "-1");

    return String.join("", result);
}