sudopower

LC: 443: String compression

lc_443

Link to problem

Solution 2 – Two pointers + in-place substitution

func compress(chars []byte) int {
    // three pointers i,j,k 
    // i moves across chars, j moves across repetitions
    // when j sees non repeated char it moves i 
    // before moving store count in-place, k moves to last written location
    // if reps>10 write digits sequentialls, incr k accordingly

    var i,j,k int
    
    for i<len(chars){
        var count int
        for j<len(chars) && chars[i]==chars[j] {
            count++
            j++
        }
        
        if count>1{
            chars[k]=chars[i]
            k++
            for _,digit:= range strconv.Itoa(count){                
                chars[k]=byte(digit)
                k++
            }
            i=j
            continue          
        } else {
            chars[k]=chars[i]
            k++
        }  

        i++
    }    

    return k

}

Solution 1 – Brute force

func compress(chars []byte) int {
    var s string
    lastSeen:=chars[0]
    var count int
    for _,curChar := range chars{
        if curChar==lastSeen{            
            count++
        } else {
            if count>1{                
                s+=string(lastSeen)+fmt.Sprintf("%d",count)                
            } else {
                s+=string(lastSeen)
            }
            lastSeen=curChar
            count=1
        }
    }

    if count>1{                
        s+=string(lastSeen)+fmt.Sprintf("%d",count)                
    } else {
        s+=string(lastSeen)
    }    
    
    for idx,char := range s{
        chars[idx]=byte(char)
    }

    return len(s)
}