[Programmer Interview Guide]-convert string format to character + number of consecutive occurrences

Source: Internet
Author: User

The conversion string format is the character in the original string + the number of consecutive occurrences of the character. For example, 1233422222 is converted to 1121324125 (1 appears once, 2 appears once, 3 appears twice ......

Similar to this question: In a word list of ultra-large text, count the number of times each word appears.

Method:

Define two variables: P, TMP, and TMP. Put the characters that are currently being counted, p the characters that have just been read, and define a count to count the number of times that the current character appears.

If TMP = P, it indicates that the same character is read again, then the number of times this character appears Count ++

If TMP! = P, it indicates that a new character should be read. output the original TMP and count, and set TMP to P, Count = 1. count the number of times the characters in P appear.

Code:

# Include <iostream> using namespace STD; int main () {char STR [50]; char TMP; int COUNT = 0; CIN> STR; char * P = STR; TMP = * P; count ++; while (* (+ + p )! = '\ 0') {If (* P = TMP) // If the characters currently read are the same as those in statistics, the number of occurrences must be ++ {count ++; continue;} cout <TMP <count; // if a new character is read, output the frequency of the characters being counted, next, count the number of occurrences of the new characters TMP = * P; Count = 1;} cout <TMP <count; // exit after reading '\ 0, the last consecutive Character Sequence is not output, so the getchar (); Return 0;} is appended here ;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.