Home > Blockchain >  Given a string s consisting of lowercase English letters, find the number of consecutive triplets wi
Given a string s consisting of lowercase English letters, find the number of consecutive triplets wi

Time:11-18

Given a string s consisting of lowercase English letters, find the number of consecutive triplets within s formed by unique characters. In other words, count the number of indices i, such that s[i], s[i 1], and s[i 2] are all pairwise distinct.

Got this on a test and was completely stumped. I am less than a year in to programming so my mind just doesn't even understand how to tackle this.

My main issue is not understanding how to get back a sum of the unique triplets.

CodePudding user response:

Loop over the possible consecutive triplets. In a given string s, there are always s.length - 2 consecutive triplets. This translates into a loop that loops s.length - 2 times.

Since each triplet is a consecutive triplet, you're really just finding slices of the string that are 3 characters in length.

To check if the 3 characters are all distinct, you can use a != b && b != c, where a, b, and c are the first, second, and third characters.

If they are distinct, you increment a variable outside the loop. When the loop is finished, simply return the variable.

function triplets(input) {
    let count = 0;
    
    for (let i = 0; i < input.length - 2; i  ) {
        const t = input.slice(i, i   3);
        
        if (t[0] !== t[1] && t[1] !== t[2]) count  ;
    }
    
    return count;
}

console.log(triplets("rabbit"));
// 2 unique triplets
// rab !
// abb
// bbi
// bit !

CodePudding user response:

const s = 'rabbit';
const triplets = [];
for(let i = 0; i < s.length; i=i 1){
  triplets.push(s.substring(i, i 3))
}
const arrTriplets = [];
triplets.forEach(function(triplet){
  const tripArr = triplet.split('');
  arrTriplets.push(tripArr)  
})
const indexesToKeep = [];
arrTriplets.forEach(function(triplet, index){
  if (triplet.length === 3 && triplet[0] !== triplet[1] && triplet[1] !== triplet[2] && triplet[0] !== triplet[2]){
    indexesToKeep.push(index);
  }
})
const result = [];
indexesToKeep.forEach(function(index){
  result.push(arrTriplets[index]);
})
console.log('n =', result.length);
console.log('result', result);

  • Related