LeetCode本地调试运行工具类
发布时间
阅读量:
阅读量
前言
进行LeetCode本地调试时,在某些情况下需要运行从网页上复制粘贴的代码。这常常让人感到繁琐重重(比如需要频繁地新建几个类)。本文采用反射机制,则实现了所有问题均可通过调用同一个方法来处理。这极大地方便了刷题时的心情。
运行
package main.java.com.wu;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/** * @author wuc
* @date 2019/12/9 9:23
*/
public class RunUtil {
static public Object run(Object... args){
try {
StackTraceElement stack = new Throwable().getStackTrace()[1];
System.out.println(stack.getClassName());
Class<?> problemClass = Class.forName(stack.getClassName());
Constructor<?> constructor = problemClass.getConstructor();
Object o1 = constructor.newInstance();
String innerClassName = problemClass.getName() + "$Solution";
Class<?> solutionClass = Class.forName(innerClassName);
Object o2 = solutionClass.getDeclaredConstructors()[0].newInstance(o1);
Method[] methods = solutionClass.getMethods();
Method method = methods[0];
Object o = method.invoke(o2, args);
System.out.println(o);
return o;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
}
数组转换
public static Object toArray(String input){
return toArray(input,null);
}
private static Object toArray(String input,int[] dimensions){
input = input.replaceAll("\ s+", "");
char[] chars = input.toCharArray();
int level = 0;
for (char aChar : chars) {
if(aChar=='['){
level++;
}
else if(aChar==']'){
break;
}
}
if(dimensions==null){
dimensions = new int[level];
}
Object arrayObject = null;
String substring = input.substring(1, input.length() - 1);
List<String> components =new ArrayList<>();
if (level == 1) {
components = Arrays.asList(substring.split(","));
} else {
// components = Arrays.asList(substring.split(",(?=\ [)"));
Stack<Integer> s = new Stack<>();
for(int i=0;i<substring.length();i++){
if('['==(substring.charAt(i))){
s.push(i);
}
else if(']'==(substring.charAt(i))){
Integer pop = s.pop();
if(s.empty())
components.add(substring.substring(pop,i+1));
}
}
}
for (int i = 0; i < components.size(); i++) {
Object o;
Class<?> contentType;
String component = components.get(i);
if(level==1) {
try {
o = Integer.parseInt(component);
contentType=int.class;
} catch (Exception e) {
try {
o = Double.parseDouble(component);
contentType=double.class;
} catch (Exception e1) {
o = String.valueOf(component);
contentType=String.class;
}
}
}
else{
o = toArray(component,dimensions);
contentType=o.getClass().getComponentType();
}
if(arrayObject==null){
int[] currDimensions = new int[level];
dimensions[dimensions.length-level]=components.size();
for(int j=0;j<level;j++){
currDimensions[j]=dimensions[dimensions.length-level+j];
}
arrayObject = Array.newInstance(contentType,currDimensions);
}
Array.set(arrayObject,i,o);
}
return arrayObject;
}
参考文章
该网页介绍了基于图灵机理论的知识表示方法,并详细阐述了其优势与应用场景。
作为人工智能领域的重要研究方向之一的知识表示技术,在本方案中得到了充分的体现与实践。
为了保证知识表示系统的高效性与可扩展性,在设计过程中充分考虑了算法的时间复杂度与空间需求。
本文主要研究了基于图灵机理论的知识表示方法,并对其性能进行了全面评估。
通过实验分析可以看出, 该方案在知识表示效率方面表现出了显著的优势。
全部评论 (0)
还没有任何评论哟~
