Java String Compression with StringBuilder

Day 21/100: String Compression & Memory 📦 Today I tackled String Compression in Java (e.g., "aaabb" -> "a3b2").  The Goal: Compress a string by counting repeated characters. Example:"aaabbc" becomes "a3b2c1". If the compressed string isn't actually shorter, return the original. Key Learning: StringBuilder vs. String In Java, strings are immutable. If you add to a string in a loop, Java creates a new object every single time. To fix this, I used **StringBuilder**, which is much faster and memory-efficient for building long strings. The Strategy: 1️⃣ Iterate through the string once. 2️⃣ Keep a running count of identical consecutive characters. 3️⃣ Append the character and count to the builder. Simple logic, big performance difference. 🚀 #100DaysOfCode #Java #DSA #Strings #Optimization #Unit2 #CodingJourney #LearnInPublic

  • text

To view or add a comment, sign in

Explore content categories