求助帖
返回一个表达式中的方法的左右括号的对应的索引位置,最好使用正则实现
如:Math.abs(Number(333.777555).toFixed(3)) - Number(123321.44455).toFixed(3)
返回左右括号的对应的索引位置为[{8,38},{15,26},{35,37},{48,61},{70,72}]
import java.util.*;
import java.util.stream.Collectors;
public class Test {
public static void main(String [] args){
Stack<Integer> stack = new Stack<Integer>();
Map keys=new HashMap<>();
String str="Math.abs(Number(333.777555).toFixed(3)) - Number(123321.44455).toFixed(3)";
for(int i=0;i<str.length();i++){
char c=str.charAt(i);
if(c=='('){
stack.push(i);
}
if(c==')'){
keys.put(stack.peek(),i);
stack.pop();
}
}
System.out.println(sortByKey(keys));
}
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
Map<K, V> result = new LinkedHashMap<>();
map.entrySet().stream()
.sorted(Map.Entry.<K, V>comparingByValue()
).forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
return result;
}
public static <K extends Comparable<? super K>, V > Map<K, V> sortByKey(Map<K, V> map) {
Map<K, V> result = new LinkedHashMap<>();
map.entrySet().stream()
.sorted(Map.Entry.<K, V>comparingByKey()
).forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
return result;
}
}