[英]Java - Prefix to Postfix using recursion
所以我正在學習數據結構課程,我們的任務是為前綴 (-+ABC) 問題制定遞歸解決方案並將其轉換為后綴 (AB+C-) 解決方案。 我覺得我有 70% 的時間......只是錯過了那點小東西。
然后返回 outputString 並將其寫入 .txt 文件。 我知道這部分工作是由於我過去合作過的實驗室。
提供的代碼在理論上應該返回 AB+C- 時返回 BCBCABCBCBCABC+ABC
public static boolean operator(char o) {
return o == '+' || o == '-' || o == '*' || o == '/' || o == '$';
}
public static String preToPost(String s) {
char[] c = s.toCharArray();
// System.out.println(c);
char ch = c[0];
//System.out.println(ch);
char[] cMinusFront = new char[s.length() - 1];
for (int i = 0, k = 0; i < c.length; i++) {
if (i == 0) {
continue;
}
cMinusFront[k++] = c[i];
}
s = String.valueOf(cMinusFront);
System.out.println(s);
String a;
String b;
String outputString = null;
if (s.length() == 1) {
return outputString;
}
if (operator(ch)) {
a = preToPost(s);
} else {
a = s.substring(0, 0);
}
if (operator(ch)) {
b = preToPost(s);
} else {
b = s.substring(0, 0);
}
outputString = a;
outputString = outputString.concat(b);
outputString = outputString.concat(String.valueOf(cMinusFront));
return outputString;
}
嘗試這個。
static boolean isOperator(char ch) {
return ch == '+' || ch == '-' || ch == '*' || ch == '/';
}
static String preToPost(StringReader input) throws IOException {
int ch = input.read();
if (ch == -1)
return "";
else if (isOperator((char)ch))
return preToPost(input) + preToPost(input) + (char)ch;
else
return "" + (char)ch;
}
static String preToPost(String input) throws IOException {
return preToPost(new StringReader(input));
}
public static void main(String[] args) throws IOException {
System.out.println(preToPost("*-+ABC"));
}
輸出:
AB+C-*
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.