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

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact