Java > String-3 > countTriple (CodingBat Solution)

Problem:

We'll say that a "triple" in a string is a char appearing three times in a row. Return the number of triples in the given string. The triples may overlap.

countTriple("abcXXXabc") → 1
countTriple("xxxabyyyycd") → 3
countTriple("a") → 0


Solution:

public int countTriple(String str) {
  int len = str.length();
  int count = 0;
  
  for (int i = 0; i < len-2; i++){
    char tmp = str.charAt(i);
    if (tmp == str.charAt(i+1) && tmp == str.charAt(i+2))
      count++;
  }
  return count;
}

1 comment:

  1. Recursively:

    public int countTriple(String str) {

    if(str.length() <= 2) return 0;
    if(str.charAt(0) == str.charAt(1) && str.charAt(0) == str.charAt(2))
    return 1 + countTriple(str.substring(1));

    return countTriple(str.substring(1));

    }

    ReplyDelete