Calculation of similarity between words with Java

0

For two string A and B, we define that the similarity of these strings is the length of the prefix that is common to both. For example, the similarity of strings abc and abd is 2, while the similarity of strings aaa and aaab is 3.

Calculate the sum of similarities of a string S with each of its suffixes, including string as the first suffix.

Input Format:

The first line contains the number of T test cases. Each of the next T lines contains string each.

Output Format:

Display T output lines, each containing an integer that is for the corresponding test case.

Assumptions:

  • 1
asked by anonymous 24.05.2017 / 23:14

2 answers

0

I was able to solve it, so the code gets cleaner:

public static void semelhancaString(Integer n, String... strings) {
List<String> listStrings;
String stringBase, stringComparator;
Integer quantidade = 0;

listStrings = new ArrayList<String>(Arrays.asList(strings));
stringBase = listStrings.get(0);

for (int j = 1; j < n; j++) {
    stringComparator = listStrings.get(j);
    quantidade = contaQuantidadeDeIgualdade(stringBase, stringComparator);
    System.out.println(
        "A suma das Semelhanças entre: " + stringBase + " e " + stringComparator + " é " + quantidade);
}
}

public static Integer contaQuantidadeDeIgualdade(String base, String comparator) {
Integer quantidade = 0;
for (int i = base.length(); i > 0; i--) {
    String substring = base.substring(0, i);
    if (comparator.contains(substring)) {
    quantidade++;
    }

}
return quantidade;
}
    
25.05.2017 / 21:47
0

Instead of passing a lot of String , it is easier if you pass as a parameter Array or List of String .

And as a return it is not possible to create a return that has T Lines of type Interger , the only way is to return a Array Integer or String

An alternative creation is the one I set up below

String[] s1 = {"ababaa", "babaa", "abaa", "baa", "aa", "a"};
String[] s2 = {"ababaa", "aa"};

private static String semelhancaString(int n, String[] s1, String[] s2) {
            StringBuilder saida = new StringBuilder();

            for (int i = 0; i < n; i++) {
                int total = 0;
                for (int j = 0; j < s1.length; j++) {
                    String palavra1 = s1[j];
                    String palavra2 = s2[i];

                    int index = 0;
                    int nComparações = 0;
                    while (index < palavra1.length() && index < palavra2.length()) {
                        if (palavra1.charAt(index) == palavra2.charAt(index)) {
                            index++;
                            nComparações++;
                        } else {
                            break;
                        }
                    }
                    total += nComparações;
                }
                saida.append(total + "\n");

            }
            return saida.toString();
        }
    
25.05.2017 / 00:11