Compression of String like (aaabbbbdddd) to (a3b4d4) in java Data Structures
Welcome!
In this post we will learn that how we can compress a String.Because when we compress String, it become short in its length, for example, if we have String (aaaabbbbccccddddffffgggghhhh)
Then it will become:
(a4b4c4d4f4g4h4)
So lets look into the algorithm for its solution:
Algorithm of Compression String
stringCompression(data:String): String
/*Now we will have StringBuilder class because, it always override the String(because we always now that String is an imputable) and it will create the same address in the heap memory and then it will make new compressed String
/*
counter:int //initial 0
buider:StringBuilder//object
for(till length of data from 1-end)
if(next character is same as previous(i==i-1?)
counter++
else
builder.append(data.charAt(i-1))
builder.append(counter)
counter=1// because it will check next characters so that counter can be again increase
/*Now at the end of the loop it will reach at the end and obviously if last is repeated then counter will increase but loop will end then we will check if counter>1 then append last character's values and iterative status in builder
*/
if(counter>1)
builder.append(data.charAt(data.length-1))
builder.append(counter);
//Now convert builder to String and return
String compressed = builder.toString()
return compressed
Comments
Post a Comment
Let me know your doubts