Cracking The Coding Interview : String Compression
Description
Implement a method to perform basic string compression using the counts of repeated characters. For example, the string?aabcccccaaa?would become?a2b1c5a3.
If the "compressed" string would not become smaller than the original string, your method should return the original string.
You can assume the string has only upper and lower case letters (a-z).
Example
Example 1:
Input: str = "aabcccccaaa"
Output: "a2b1c5a3"
Example 2:
Input: str = "aabbcc"
Output: "aabbcc"
Solution
The solution to this problem involves trivial string manipulation with two pointers approach. First we create a?copy?string and will call it a "dummy String" with an extra delimiter character. After that will declare two pointers one will mark the start of the similar consecutive chars and the second one will indicate the end of the similar consecutive chars and when we hit two chars not similar will append the repetitive char with the number of repetitions. Finally will check if the length of the final compressed string is smaller than the original chars to apply mentioned condition
"If the "compressed" string would not become smaller than the original string, your method should return the original string."
TechOps Engineer @Sumerge | SRE | DevOps
2 å¹´?????? ?? ???? ??? ??????? ?????? ??
Senior SDE @ Pixelogic Media | ex-Orange Labs | Backend Enthusiast
2 å¹´???? feedback ???? ??? ???? ????? documented ????? ??? ????? ???? ? follow up ??? ??????? ??????? ????? ???? ???? ?? ????? ?? ???? ???? ?? ???? ?? articles ????? LinkedIn