Function which counts multiplies chars in a String

Viewed 209

For my Homework I need to count chars in a String. If there are more than three of the same char behind each other the method schould return true if not false.

Now develop a method noMultiples (), which checks if there are three (or more) equal characters in a string Generalize noMultiples () now,that the number of characters to be repeated is parameterized.

I alredy tried to spilt the String in to substrings but received an String index out of Bounds error. Also i tried to work with the charAt() method but I am kinda stuck now. Are there any ways to solve this problem ? Thanks in advance

 public static boolean noMultiples(int n, String s) {
    for(int i=0;i<s.length();i++){
        if(s.charAt(i)==s.charAt(i+1)&&s.charAt(i+1)==s.charAt(i+2)){
            return true;
        }
    }
    return false;
}

This should be the expected output :

public static void main(String[] args) {
    boolean result = noMultiples("Hello World");
    System.out.println(result); // => true
    System.out.println(noMultiples("faaantastic")); // => false
    System.out.println(noMultiples(2, "Hello World")); // => false
}
3 Answers

You may use some field inside the method to store the amount of char repetitions.

Also, overload noMultiples to accept only the string.

Note: since noMultiples return true if it found multiple consecutive chars, it's better to name this method containsMultiples. By doing so it will be more intuitive in the future, where you will modify or use it later.

public class test
{
    public static void main(String[] args)
    {
        System.out.println(containsMultiples("Hello World"));
        System.out.println(containsMultiples("faaaantastic"));
        System.out.println(containsMultiples(2, "Hello World"));
    }

    public static boolean containsMultiples(int n, String s) {
        int len = s.length();
        if(len == 0) return false;
        char lastChar = s.charAt(0);
        int multipliesFound = 1;

        for(int i = 1; i < len; i++) {
            if(s.charAt(i) == lastChar) {
                multipliesFound++;
            }
            else {
                multipliesFound = 1;
            }
            if(multipliesFound == n) {
                return true;
            }
            lastChar = s.charAt(i);
        }
        return false;
    }

    public static boolean containsMultiples(String s) {
        return containsMultiples(3, s);
    }
}

returns:

false
true
true

Based on your examples for the Hello World string, I assumed you're looking for a method to find only consecutive equals chars.

My idea is to create a HashMap for character and integer pairs, and put the characters and their count in it!

public boolean noMultiples(int maxMultiples, String myString) {
    HashMap<Character, Integer> map = new HashMap<>();
    for(int i=0; i<myString.length(); i++) {
        char c = myString.charAt(i);
        if(map.containsKey(c)) {
           int prevCount = map.get(c);
           map.put(c, prevCount+1); //we found one more of this character
        } else {
           map.put(c, 1); //first occurence
        }
    }
    //here our map is filled with characters and their count in the string
    for(int charCount: map.values()) {
       if(charCount >= maxMultiples) return false; //found a multiple
    }
    return true; //not found a large enough multiple
}

This could be optimized a bit by returning false from the first loop if we encounter a large enough value there, but this way the filled hash map can be used to further generalize the method.

shorter is a solution with lambda

public static boolean noMultiples(int n, String s) {
  return s.codePoints().distinct().allMatch( c -> {
    int from = 0;
    while( (from = s.indexOf( c, from )) >= 0 ) {
      for( int i = from, count = 1; i < s.length() && c == s.charAt( i ); i++ ) {
        if( count++ >= n )
          return( false );
      }
      from++;
    }
    return( true );
  } );
}

find all distinct characters of String s first
then check if the number of all consecutive occurrences is less than n
faster would be to check the opposite – are there any multiples – if time plays a role

Related