2016年网易笔试编程题2

题目描述:

输入共两行,第一行为字典,以空格为界限,为一个个字符串

第二行为用户输入,同样以空格为界限的一个个字符串。

要求:找出输入的字符串是否在字典里,若不在,输出该字符串,并考虑是否能通过增加一个或者减少一个或者修改一个字符串来自动补全,输出修正后的字符串。

解题思路:

很容易想到求最长公共子串,考虑最长公共子串的长度和字典以及输入的关系。

代码:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            String dicts[] = scanner.nextLine().split(" ");
            String words[] = scanner.nextLine().split(" ");

            for (String word : words) {
                boolean found = false;

                for (int i = 0; i < dicts.length; i++) {
                    int lend = (dicts[i]).length();
                    int lenw = word.length();
                    if (lend != lenw) {
                        break;
                    }

                    int lcs = lcs(dicts[i], word);

                    if (lcs == word.length()) {
                        found = true;
                        break;
                    }
                }
                if (found == false) {
                    System.out.print(word + " ");
                    for (int i = 0; i < dicts.length; i++) {
                        int lcs = lcs(dicts[i], word);
                        boolean flag = false;
                        if (word.length() <= dicts[i].length()) {
                            flag = (dicts[i].length() - lcs) == 1;
                        } else if (word.length() > dicts[i].length()) {
                            flag = (word.length() - lcs) == 1;
                        }
                        if (flag == true) {
                            System.out.print(dicts[i] + " ");
                        }
                    }
                    System.out.println();
                }
            }

        }
    }

    public static int lcs(String dict, String word) {
        int lend = dict.length();
        int lenw = word.length();

        int[][] value = new int[lend + 1][lenw + 1];

        for (int i = 0; i < lend; i++)
            value[i][0] = 0;
        for (int i = 0; i < lenw; i++)
            value[0][i] = 0;

        for (int i = 1; i <= lend; i++) {
            for (int j = 1; j <= lenw; j++) {
                if (dict.charAt(i - 1) == word.charAt(j - 1)) {
                    value[i][j] = value[i - 1][j - 1] + 1;
                } else {
                    if (value[i - 1][j] > value[i][j - 1])
                        value[i][j] = value[i - 1][j];
                    else {
                        value[i][j] = value[i][j - 1];
                    }
                }
            }
        }
        return value[lend][lenw];

    }

}
原文地址:https://www.cnblogs.com/Run-dream/p/5313229.html