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; }
public int countTriple(String str) {
ReplyDeleteint 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.
public int countTriple(String str) {
ReplyDeleteint 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;
}
I came up with the exact same solution :D
Deletepublic int countTriple(String str) {
ReplyDeleteint 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;
}
public int countTriple(String str) {
ReplyDelete//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;
}
}
public int countTriple(String str) {
ReplyDeleteint 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;
}
def countTriple(s):
ReplyDeletec = 0
for i in range(len(s)-2):
if s[i] == s[i+1] == s[i+2]:
c += 1
return c