Question:
Enter a string of lowercase letters (~ Z. Compile a character string compression program to compress duplicate letters that are present continuously in the string and output the compressed character string.
Compression rules:
1. Only compress the repeated characters. For example, the compressed string "abcbc" is still "abcbc" because there are no consecutive duplicate characters ".
2. The format of the compressed field is "repeated characters + characters ". For example, after the string "xxxyyyyz" is compressed, it becomes "3x6yz ".
Required implementation functions:
Void stringzip (const char * pinputstr, long linputlen, char * poutputstr );
[Input] pinputstr: input string
Linputlen: length of the input string
[Output] poutputstr: Output string. The space has been opened up and the length of the input string is equal to that of the input string;
[Note] You only need to complete the function algorithm, and there is no IO input or output in the middle.
Example
Input: "cccddecc" output: "3c2de2c"
Input: "adef" output: "adef"
Input: "pppppppp" output: "8 P"
Analysis: character compression is used to determine the number of identical characters, and then the characters are prefixed with the number, so we can count the characters and splice them again.
Here I come up with two methods,
1: create two lists, one for storing characters, and the other for storing the number of characters. Then, recombine the strings based on the two lists;
2: directly combine strings in the counting process
Here I chose the second approach. I felt that I could write less code and I was too lazy!
The Code is as follows:
Package com. wenj. test;
/*
* @ Author wenj91-PC
*
*/
Public class teststringzip {
Public static void main (string ARGs []) {
String strin = "pppppppp ";
Teststringzip Ts = new teststringzip ();
System. Out. println (TS. stringzip (strin ));
}
Public String stringzip (string strin ){
String strtemp = strin;
Char [] STRC = strtemp. tochararray ();
String temp = ""; // stringbuffer is suitable for use here, but it is easy for readers to pay attention to it.
Int COUNT = 0;
Char prechar = STRC [0];
For (INT I = 0; I <STRC. length; I ++ ){
Char ctemp = STRC [I];
If (ctemp = prechar) {// determine whether the character is the same as the previous one
Count ++;
} Else {
If (count> 1 ){
Temp + = count;
}
Count = 1;
Temp + = prechar;
Prechar = STRC [I];
}
If (I = STRC. Length-1) {// determine whether the end is reached
If (count> 1 ){
Temp + = count;
}
Temp + = STRC [I];
}
}
Return temp;
}
}