1 回答

TA貢獻(xiàn)1909條經(jīng)驗(yàn) 獲得超7個(gè)贊
這是你如何做到這一點(diǎn)。
首先,請(qǐng)注意一點(diǎn)。這行代碼是多余的:
private static final String DIGITS = "0123456789";
如果你想檢查一個(gè)字符是否是數(shù)字,你可以簡(jiǎn)單地做到這一點(diǎn)
Character.isDigit();
但為了簡(jiǎn)單起見(jiàn),我保留了這條線。
現(xiàn)在,回到你的代碼。為了提供解析多位數(shù)字的功能,您所要做的就是在遇到數(shù)字時(shí)循環(huán)訪問(wèn)輸入字符串,直到第一個(gè)非數(shù)字字符。
我對(duì)你的代碼進(jìn)行了一些更改,以向您展示它應(yīng)該如何工作的基本想法:
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)))
添加回答
舉報(bào)