例如: 如果輸入是(5 * x)將返回的結果是: 「括號正確放置」如何確定密文表達式中第一個冗餘括號的索引?
如果輸入是(((5 * x)將返回的結果是: 「括號被置於不正確冗餘開括號的」 「數量:3」
如果輸入是(5 * X)+ 10 * Y)+ 5 * z)的我的返回結果必須是: 「括號放置不當」 「第一個冗餘右括號索引:10」 - 這是我不明白該怎麼辦.................
如何實現一個輸出,該輸出顯示第一個重複右括號的索引?
這是我的代碼:
public static void main(String[] args) {
System.out.println("Enter an arithmetic expression:");
Scanner in = new Scanner(System.in);
String arithmeticExpression = in.nextLine();
System.out.println(parenthesesCheckup(arithmeticExpression));
}
public static String parenthesesCheckup(String arithmeticExpression) {
char openingParenthesis = '(';
char closingParenthesis = ')';
Stack<Character> stack = new Stack<Character>();
char array[] = arithmeticExpression.toCharArray();
for (char current : array) {
if ((current == closingParenthesis) && stack.empty()) {
stack.push(current);
char previousStack = stack.peek();
switch (current) {
case ')':
if (previousStack == '(')
stack.pop();
return "Parentheses are placed incorrectly\n" +
"Index of first redundant closing parenthesis: ";
}
}
if (current == openingParenthesis) {
stack.push(current);
}
if ((current == closingParenthesis) && !stack.empty()) {
char previousStack = stack.peek();
switch (current) {
case ')':
if (previousStack == '(')
stack.pop();
break;
}
}
}
if (stack.empty()) {
return "Parentheses are placed correctly";
} else {
return "Parentheses are placed incorrectly\n" +
"Quantity of redundant opening parenthesis: " + stack.size();
}
}
}
什麼預計會出現這樣的輸入:'5 + 3)+(2 + 1'? – SergeyS
這看起來像一個「請爲我做功課」的問題。請考慮本指南在SO上編寫一個好問題:https:// codeblog .jonskeet.uk/2012/11/24/stack-overflow-question-checklist/ –
@SergeyS,這樣的輸入不是預期的:) –