Super Reduced String

  • + 0 comments

    SWIFT

    func logic(charCount: Int, strings: [UInt8], string: UInt8) -> [UInt8] {
        var newStrings: [UInt8] = strings
        
        if charCount % 2 == 1 {
            if newStrings.last ?? 0 == string { newStrings.popLast() }
            else { newStrings.append(string) }
        }
    
        return newStrings
    }
    
    func superReducedString(s: String) -> String {
        // Write your code here
        var oldStrings: [UInt8] = [UInt8](s.utf8)
        var newStrings: [UInt8] = [UInt8]()
        
        var strTemp: UInt8 = oldStrings.first!
        var charCount: Int = 0
            
        for index in 0 ... oldStrings.count - 1 {
            if oldStrings[index] == strTemp {
              charCount += 1
              continue
            }
            
            newStrings = logic(charCount: charCount, strings: newStrings, string: oldStrings[index - charCount])
            strTemp = oldStrings[index]
            charCount = 1
        }
            
        newStrings = logic(charCount: charCount, strings: newStrings, string: oldStrings[oldStrings.count - 1])
        
        return newStrings.count == 0 ? "Empty String" : String(bytes: newStrings, encoding: String.Encoding.utf8) ?? ""
    }