# 最少替換達成不連續字串

/* example
input ["bok", "book", "boook", "booook"]
output [0,1,1,2]  boook 變成 boaok 就沒有連續 

input  ['book', 'booooookoooo']
output [1,5]
*/

function minimalOperations(words) {
 
  return words.map(word => {
     const len = word.length
     if(len < 2) return 0
     let count = 0
     for(let i=1; i<len; i++){
       const prev = word[i-1]
       const cur = word[i]
       const next = word[i+1] || null
      
       
       if(next && prev===cur && cur===next){
         count++;
         i++
         continue
       }
       if(prev===cur){
         count++;
       }
     }
    
    return count
  })
  
}

8/12/2025

function minimalOperations(words) {
  return words.map( word =>  runLengthEncode(word))
}
  
  
  function runLengthEncode(word){
    let len = word.length;
    if(len < 2) return 0
    let count = 0
    
    for(let L=0; L<len -1; L++){
      let R = L + 1
     
      if(word[L] === word[R]){
        count ++;
        L++;
      }
    }
    return count
  }

Last updated

Was this helpful?