[2013 Baidu software development pen questions] calculate the maximum number of consecutive occurrences of the same character in the string

Source: Internet
Author: User

The full description of the question is: recursively calculate the maximum number of consecutive occurrences of the same character in a string, such as aaabbcc. the maximum number of consecutive occurrences of A is 3, abbc, the maximum number of consecutive characters is 2.


The following are my methods:

# Include <iostream> using namespace STD; # define max (a, B) (a)> (B )? (A): (B) int get (char * s, int N, int m) // character pointer, the longest string currently, max longest string {If (* (S + 1) = '\ 0') return max (n, m); If (* s = * (S + 1 )) return get (S + 1, n + 1, m); return get (S + 1, 1, max (n, m);} int main () {printf ("% d \ n", get ("abbc", 1, 1); printf ("% d \ n", get ("aaabbcc", 1, 1); getchar (); Return 0 ;}

And another recursive method:

#include <iostream>using namespace std;int Get(char *s){    int ans = 0;    char *t = s;    if(*s == '\0')        return ans;    while(*s != '\0' && *t == *s)        ans++, s++;    t++;    int tmp = Get(t);    return ans > tmp ? ans : tmp;}int main(){    printf("%d\n", Get("abbc"));    printf("%d\n", Get("aaabbcc"));    getchar();    return 0;}
I don't know why it must be recursive... Maybe we want to test the ability to write recursion. It doesn't matter. Anyway, the test questions are weird -.-

If you have other better methods, please kindly advise!

[2013 Baidu software development pen questions] calculate the maximum number of consecutive occurrences of the same character in the string

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.