(Cybercode) Letter Count I - Solução

Have the function LetterCountI(str) take the str parameter being passed and return the first word with the greatest number of repeated letters. For example: "Today, is the greatest day ever!" should return greatest because it has 2 e's (and 2 t's) and it comes before ever which also has 2 e's. If there are no words with repeating letters return -1. Words will be separated by spaces.

Solução:

import java.util.*;
import java.io.*;

class Function { 
  String LetterCountI(String str) {
    String[] palavras = str.split(" ");
   
    final String LETRAS = "abcdefghijklmnopqrstuvwxyz";
    /* Em vez do vetor, poderia ter utilizado uma matriz também,
     * cada linha seria referente a uma palavra */
    int[] vetorContaLetras = new int[26]; // onde fica o contador de letras de cada palavra
   
    int maiorGeral = -1; // para ver qual a palavra tem mais letras repetidas
   
    String palavraRequerida = "";
    for (int i = 0; i < palavras.length; i++) {
      int maiorAparicao = -1; // para ver qual letra aparece mais em uma palavra
     
      String palavra = palavras[i].toLowerCase();
      for (int j = 0; j < palavras[i].length(); j++) {
          vetorContaLetras[LETRAS.indexOf(palavra.charAt(j))]++;
      }
      for (int j = 0; j < palavras[i].length(); j++) {
        if (vetorContaLetras[LETRAS.indexOf(palavra.charAt(j))] > maiorAparicao) {
            maiorAparicao = vetorContaLetras[LETRAS.indexOf(palavra.charAt(j))];
        }
        vetorContaLetras[LETRAS.indexOf(palavra.charAt(j))] = 0; // já foi verificado, reseto o valor
      }
      if (maiorAparicao > maiorGeral) {
           maiorGeral = maiorAparicao;
        palavraRequerida = palavras[i];
      }
     
      maiorAparicao = -1;
    }
      
    if (maiorGeral == 1) { // se a palavra com mais letras repetidas só possui letras que aparecem uma única vez, não existem letras repetidas
        return "-1"; 
    }
   
    return palavraRequerida;
   
  }
 
  public static void main (String[] args) { 
    // keep this function call here    
    Scanner  s = new Scanner(System.in);
    Function c = new Function();
    System.out.print(c.LetterCountI(s.nextLine()));
  }  
 
}

Comments

Popular posts from this blog

(Coderbyte) Dash Insert II - Solução

(Coderbyte) Run Length - Solução

(Coderbyte) Counting Minutes I - Solução