1 条题解
-
0
JAVA题解:
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); // 读取最短提示距离D int D = Integer.parseInt(reader.readLine().trim()); // 读取子命令数量N int N = Integer.parseInt(reader.readLine().trim()); // 读取所有子命令 List<String> commands = new ArrayList<>(); for (int i = 0; i < N; i++) { commands.add(reader.readLine().trim()); } // 读取用户输入的命令 String userInput = reader.readLine().trim(); // 计算并输出结果 String result = findSimilarCommands(D, commands, userInput); System.out.println(result); } /** * 查找与用户输入相似的命令 * * @param D 最短提示距离 * @param commands 可用的子命令列表 * @param userInput 用户输入的命令 * @return 提示结果 */ public static String findSimilarCommands(int D, List<String> commands, String userInput) { // 精确匹配检查 if (commands.contains(userInput)) { return userInput; } // 计算编辑距离并筛选符合条件的命令 List<CommandDistance> candidates = new ArrayList<>(); for (String cmd : commands) { int distance = calculateEditDistance(userInput, cmd); if (1 <= distance && distance <= D) { candidates.add(new CommandDistance(cmd, distance)); } } // 如果没有符合条件的命令 if (candidates.isEmpty()) { return "None"; } // 按编辑距离和字典序排序 Collections.sort(candidates); // 构建结果字符串 StringBuilder result = new StringBuilder(); for (int i = 0; i < candidates.size(); i++) { if (i > 0) { result.append(" "); } result.append(candidates.get(i).command); } return result.toString(); } /** * 计算两个字符串之间的莱文斯坦编辑距离 * * @param s1 第一个字符串 * @param s2 第二个字符串 * @return 编辑距离 */ public static int calculateEditDistance(String s1, String s2) { int m = s1.length(); int n = s2.length(); // 创建DP表 int[][] dp = new int[m + 1][n + 1]; // 初始化第一行和第一列 for (int i = 0; i <= m; i++) { dp[i][0] = i; } for (int j = 0; j <= n; j++) { dp[0][j] = j; } // 填充DP表 for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if (s1.charAt(i - 1) == s2.charAt(j - 1)) { dp[i][j] = dp[i - 1][j - 1]; } else { dp[i][j] = 1 + Math.min( Math.min(dp[i - 1][j], // 删除 dp[i][j - 1]), // 插入 dp[i - 1][j - 1] // 替换 ); } } } return dp[m][n]; } /** * 命令和距离的包装类,用于排序 */ static class CommandDistance implements Comparable<CommandDistance> { String command; int distance; public CommandDistance(String command, int distance) { this.command = command; this.distance = distance; } @Override public int compareTo(CommandDistance other) { // 首先按距离排序,然后按字典序 if (this.distance != other.distance) { return Integer.compare(this.distance, other.distance); } return this.command.compareTo(other.command); } } }
- 1
信息
- ID
- 20
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 5
- 标签
- 递交数
- 2
- 已通过
- 1
- 上传者