簡體   English   中英

java中綴表達式推導

[英]java infix expression derivation

我有 2 個字符串

String expression = add(,subtract(,));

String values = (3,(10,4));

我想評估表達式。所以 output 應該如下所示。

add(3 , subtract(10,4) )

我嘗試了什么:我嘗試的方法是從表達式中刪除特殊字符,標記化並將 function 名稱存儲在一個數組中。所以在上面的例子中,數組將有加法,減法。 然后,循環並用 add(3) 替換 3 和用減法 (10,4) 替換 10,4。 如果我只有 1 或 2 個功能,我會得到想要的 output。 但是如果有多個嵌套函數,我無法為如下表達式推導出 output。

例如:

 expression= add(subtract(,) , multiply(,)) 
 value = ( (4,3)  , (2,2) )  

output = add( subtract(4,3) , multiply(2,2))

您可以嘗試以下過程來實現您的結果:

建議的程序:

//base case
1. if count of'(' != count of ')' // unbalanced parenthesis
    print 'Invalid Expression'
    exit the program
2. Store all the operations (like add, subtract, multiply,etc.) from the expressions string.
3. for char ch in values
     replace each occurrence of open parenthesis(() with  stored operation in step 2 along with (.

上述程序在java中的實現(我建議您嘗試自己的方式來實現上述程序。代碼可以進一步優化):

import java.util.ArrayList;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Main{
// Regex to extract all the operations from the expression string.
    private static final Pattern pattern = Pattern.compile("\\w+");
    public static void main(String[] args){
        String expression = "add(divide(add(,),) , subtract(,))";
        String value = "(((5 , 5), 2),(10,4))";

        StringBuilder sb = new StringBuilder(); // To store the final result.
        Matcher matcher = pattern.matcher(expression);
        ArrayList<String> arr = new ArrayList<>(); //to store all the operations from the expression string.
        if(count(value, '(') != count(value,')')){
            System.out.println("Invalid expression");
            System.exit(0);
        }
        while(matcher.find())
            arr.add(matcher.group(0));
        int counter = 0;
        for(char ch: value.toCharArray()){
            if(ch == '('){
               sb.append(arr.get(counter) + "(");
               // counter only gets incremented if operations get appended to sb
               counter++;
            }
            else sb.append(ch);
        }
        System.out.println(sb.toString());
    }
// utility method to fulfill step 1 of proposed procedure.
    public static int count(String str, char ch){
        int count = 0;
        for(char chr:str.toCharArray()){
            if(chr == ch)count++;
        }
        return count;
    }
}

您可以在此處找到上述實現的示例運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM