CC-12 : Implement basic compression.
Description:
Basic compression compresses strings like “pppqqsaaaab” to “p3q2s1a4b1”. Given input String str, implement basic compression on the same and return the compresses String.
Test cases and expected outputs:
| Input Parameters | Expected outputs |
|---|---|
| aaaabczaa | a4b1c1z1a2 |
| sdddeff | s1d3e1f2 |
Pseudocode:
| The java method should accept following input parameters: str (String). |
| Initialize a new StringBuilder instance named sb. We will use sb to assemble the compressed String. |
| Initialize char variable currChar to “”. We will use currChar to store the current character we have traversed in str. |
| Initialize int variable charCnt to 0. We will use this variable to store the count of consecutive repetitions of currChar that we have found. We will use this count of repetition while constructing the compressed String. |
| Initialize int variable currIdx to 0. |
| Iterate through str using while loop with condition currIdx < str.length():
Set currChar to str.charAt(currIdx).
Set charCnt to 1, as we have found 1 instance of currChar till now.
Now we need to check how many times currChar repeats. Iterate through str using while loop till str.charAt(currIdx)==currChar and currIdx < str.length():
Increment charCnt by one as we have found a repletion of currChar.
Increment currIndex by one.
o At end of inner while loop append currChar in sb. Append charCnt also in sb, this is the count of repetitions of currChar found in str.
|
| At the end of outer loop, the compressed String is assembled in sb. Extract compressed String from sb by StringBuilder.toString() method and return the compressed String. |
Code:
public String stringCompress(String str) {
StringBuilder sb=new StringBuilder();
char currChar='\0'; int charCnt=0;
int currIdx=0;
while (currIdx < str.length()) {
currChar=str.charAt(currIdx);
charCnt=1; currIdx++;
while ((currIdx < str.length())&&(str.charAt(currIdx)==currChar)){
charCnt++; currIdx++;
}
sb.append(currChar);sb.append(charCnt);
}
return sb.toString();
}
Click here to download and run code and test cases !
| About Us | Privacy Policy | Contact us |