Social Icons

Saturday, April 10, 2010

countTriple: Solutions for Javabat : 06


Here we go with another String question.

 

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

My Solution: For we have to iterate through the characters of the given string we definitely  should use a loop and check whether the adjacent two chars is the same as the current char. for overlaps should be considered we must not alter the iteration.

  1: public int countTriple(String str) {
  2: 
  3:   if(str.length()<3) return 0;
  4:   
  5:   int triples=0;
  6:   
  7:   for(int i=0 ; i<str.length()-2;i++){
  8:      if(str.charAt(i)== str.charAt(i+1) && str.charAt(i)== str.charAt(i+2) )
  9:         triples++;
 10:   }
 11: 
 12:   return triples;
 13: 
 14: }
 
 
Blogger Templates http://slots.to/