在 IDE 中测试 leetcode 中的代码时,当输入数据规模比较大,如果直接赋值,会报 “代码过长“ 的错误,看网上的评论,似乎可以通过修改 IDE 的配置来解决该问题,但是主程序中放置超长的数据,非常的不优雅。因此,可以做一个从文件读取输入数据的转接。
主要涉及的知识点是从文件读取数据,针对 leetcode 问题:815.公交路线,主要的任务是将 文件中的数据读取到数组,相关的功能代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
|
String[] str = new String[3];
try {
Path path = Paths.get("src/data.txt"); List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8); for(int i = 0; i < 3; ++i){ str[i] = lines.get(i); } } catch (IOException e) { e.printStackTrace(); }
str[0] = str[0].substring(1, str[0].length()-2);
String[] routesData = str[0].split("],"); int[][] routes = new int[routesData.length][]; for(int i = 0; i < routesData.length; ++i){ String[] routeData = routesData[i].substring(1).split(","); int[] route = new int[routeData.length]; for(int j = 0; j < routeData.length; ++j){ route[j] = Integer.parseInt(routeData[j]); } routes[i] = route; } int source = Integer.parseInt(str[1]); int target = Integer.parseInt(str[2]);
|