Topic:
A string of lowercase letters (A~Z) entered through the keyboard. Write a string compression program that compresses the repeated letters that appear in the string and outputs the compressed string.
Compression rule:
1, only the consecutive repeated occurrences of the character compression. For example, the string "ABCBC" because there is no consecutive repeated characters, compressed string or "ABCBC."
2, the Compressed field format is "the number of repeat characters + characters." For example, the string "Xxxyyyyyyz" becomes "3x6yz" after compression.
Required implementation function:
void Stringzip (const char *PINPUTSTR, long Linputlen, Char *poutputstr);
"Enter" PINPUTSTR: input string
Linputlen: Input string length
"Output" POUTPUTSTR: output string, space has been opened up, with the input string equal length;
"Note" Only need to complete the function algorithm, the middle does not require any IO input and output
Example
Input: "CCCDDECC" output: "3c2de2c"
Input: "adef" output: "Adef"
Input: "PPPPPPPP" output: "8p"
Analysis: Here the character compression is to judge the number of the same characters, and then the number of characters prefixed, so we can count the characters, and then splicing again
Back to the column page: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/
Here I think of two ways,
1: Is to create two list, a storage character, one is the number of characters stored, and then according to the two list to regroup the string;
2: Combine strings directly in the process of counting
Here I choose to be the second way of thinking, feeling will write less code, steal a lazy slightly, hehe!
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 ();
The String temp = "";//here with StringBuffer is more appropriate, but the individual lazy toss, the reader's words to pay attention to the good of int count = 0;
Char Prechar = strc[0];
for (int i=0; i< strc.length; i++) {char ctemp = strc[i];
if (ctemp = = Prechar) {//judge whether the character is the same as the previous character count++;
}else{if (count>1) {temp = count;
Count = 1;
temp = Prechar;
Prechar = Strc[i];
} if (i==strc.length-1) {//Determine if to end if (count>1) { temp = count;
Temp + = Strc[i];
} return temp; }
}
Author: csdn Blog zlw420123