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;
}

7 comments:

  1. public int countTriple(String str) {
    int tripCount = 0;
    for(int i=0;i<str.length()-2;i++)
    {
    if(str.charAt(i+1) != str.charAt(i+2))
    i++;
    else if(str.charAt(i) == str.charAt(i+1))
    tripCount++;
    }
    return tripCount;
    }

    I think this might be better because you skip a character if you know the i+1 and i+2 are unequal.

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

    ReplyDelete
  3. public int countTriple(String str) {
    int p=0;
    if(str.length()>2)
    {
    for(int i=0;ii+2&&str.charAt(i)==str.charAt(i+1)&&str.charAt(i)==str.charAt(i+2))
    {
    p=p+1;

    } } }
    return p;
    }

    ReplyDelete
  4. public int countTriple(String str) {
    //Recursion Rocks!!//
    if (str.length() < 3)
    {
    return 0;
    }
    else
    {
    int count = 0;
    if (str.charAt(0) == str.charAt(1) && str.charAt(1) == str.charAt(2))
    {
    count = countTriple(str.substring(1)) + 1;
    }
    else
    {
    count = countTriple(str.substring(1));
    }
    return count;
    }
    }

    ReplyDelete
  5. public int countTriple(String str) {
    int c=0;
    for(int i=0;i<str.length()-2;i++){
    if(str.charAt(i)==str.charAt(i+1))
    if(str.charAt(i+1)==str.charAt(i+2))
    c++;
    }
    return c;
    }

    ReplyDelete
  6. def countTriple(s):
    c = 0
    for i in range(len(s)-2):
    if s[i] == s[i+1] == s[i+2]:
    c += 1
    return c

    ReplyDelete