1 回答

TA貢獻1909條經驗 獲得超7個贊
這是你如何做到這一點。
首先,請注意一點。這行代碼是多余的:
private static final String DIGITS = "0123456789";
如果你想檢查一個字符是否是數字,你可以簡單地做到這一點
Character.isDigit();
但為了簡單起見,我保留了這條線。
現在,回到你的代碼。為了提供解析多位數字的功能,您所要做的就是在遇到數字時循環訪問輸入字符串,直到第一個非數字字符。
我對你的代碼進行了一些更改,以向您展示它應該如何工作的基本想法:
private static final String DIGITS = "0123456789";
public static String convertPostfixtoInfix(String toPostfix)
{
LinkedStack<String> s = new LinkedStack<>();
StringBuilder digitBuffer = new StringBuilder();
/* I've changed the 'for' to 'while' loop,
because we have to increment i variable inside the loop,
which is considered as a bad practice if done inside 'for' loop
*/
int i = 0;
while(i < toPostfix.length())
{
if(DIGITS.indexOf(toPostfix.charAt(i)) != -1)
{
//when a digit is encountered, just loop through toPostfix while the first non-digit char is encountered ...
while (DIGITS.indexOf(toPostfix.charAt(i)) != -1) {
digitBuffer.append(toPostfix.charAt(i++)); //... and add it to the digitBuffer
}
s.push(digitBuffer.toString());
digitBuffer.setLength(0); //erase the buffer
}
//this if-else can also be replace with only one "if (toPostfix.charAt(i) != ' ')"
else if(toPostfix.charAt(i) == ' ');{}//do nothing for blank.
else
{
String temp = "";
temp += toPostfix.charAt(i);
String num1 = s.top();
s.pop();
String num2 = s.top();
s.pop();
s.push("(" + num2 + temp + num1 + ")");
}
i++;
}
return s.top();//top() is same as peek() method.
}
輸入: 40 5 - 9 20 1 + / *
輸出: ((40-5)*(9/(20+1)))
添加回答
舉報