首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

大一 c++ 最好能解释一上思路

2012-12-14 
大一 c++ 最好能解释一下思路编写函数,求出一个字符串(只包含a,b,*三个字符)中连续的a或连续的b、或连续的*

大一 c++ 最好能解释一下思路
编写函数,求出一个字符串(只包含a,b,*三个字符)中连续的a或连续的b、或连续的*出现的最大次数。
在主函数中从键盘输入长度不超过100的字符串(只包含a,b,*三个字符),调用函数并输出结果。
例如:输入abbbaaa***ab***bbbaaaab,输出:4,a;输入*abbbaab**aaabbbb*****abb,输出:5,*
[最优解释]
首先遍历字符串,然后建立三个计数器,分别记录a b *的连续次数,判断是否连续很简单,就是下一个和当前的比较。等字符串遍历完之后,判断计数器大小。取最大的输出就行。
[其他解释]

#include <iostream>
using namespace std;

int main()
{
char str[100] = {'\0'};
cin.getline(str, 100);
char c;
c = str[0];
int cnt[100] = {0};
int j = 0;
cnt[0] = 1;
for(int i = 1; i < sizeof(str); i++){
if(c == 'a' 
[其他解释]
 c == 'b' 
[其他解释]
 c == '*'){
if(str[i] == c){
cnt[j] ++;
}
else{
j ++;
cnt[j] = 1;
c = str[i];
}
}

}
int cnt_max = cnt[0];
for(int i = 1; i < 100; i++){
if(cnt_max < cnt[i]){
cnt_max = cnt[i];
}
}
cout << cnt_max << endl;

system("pause");
return 0;
}



[其他解释]

#include <stdio.h>

#define MAX_CHARS(100)

int main(int argc, char* argv[])
{
char str[MAX_CHARS + 1];
char* p = str;
char ch = 0;
char maxc;
int count = 0;
int i;

fgets(str, MAX_CHARS, stdin);

while(*p)
{
if(ch == 0)
{
ch = *p++;
count = 0;
i = 1;
}
else
{
if(*p == ch)
{
p++;
i++;
}
else
{
if(count < i)
{
maxc = ch;
count = i;
}
ch = *p++;
i = 1; 
}
}
}

printf("%d, %c\n", count, maxc);

return 0;
}

[其他解释]
见笑了,呵呵,写文章需要琢磨。

引用:
引用:C/C++ code??



123456789101112131415161718192021222324252627282930313233343536373839404142434445464748

#include <stdio.h>   #define MAX_CHARS    (100)   int mai……

[其他解释]
经过本人测试,这份代码可用。
思路很简单,三个数字分别记录连续的a, b, *的最大长度


#include <iostream>
#include <string>
using namespace std;

//统计连续a,b,*的最大长度
int CountFun(string &str) //形参要为引用
{
int nCount[3] = {0};
int nMax = 0;
for (int i = 0; i < str.length(); i++)
{
if (str[i] == 'a')


{
nCount[0]++;
nCount[1] = 0;
nCount[2] = 0;
if (nCount[0] > nMax)
nMax = nCount[0];
}
else if (str[i] == 'b')
{
nCount[0] = 0;
nCount[1]++;
nCount[2] = 0;
if (nCount[1] > nMax)
nMax = nCount[1];
}
else if (str[i] == '*')
{
nCount[0] = 0;
nCount[1] = 0;
nCount[2]++;
if (nCount[2] > nMax)
nMax = nCount[2];
}
}
return nMax;
}

int main()
{
cout<<"By MoreWindows (http://blog.csdn.net/MoreWindows)"<<endl;
string str;
cin>>str;
//str = "abbbaaa***ab***bbbaaaab";
//str = "*abbbaab**aaabbbb*****abb";
cout<<CountFun(str)<<endl;
return 0;
}


[其他解释]
初始化一个长度为3的数组,表示每一个符号连续的次数,当下一次连续的次数大于当前值时就更新,最后比较这三个值的大小。
[其他解释]
引用:
C/C++ code??



123456789101112131415161718192021222324252627282930313233343536373839404142434445464748

#include <stdio.h>   #define MAX_CHARS    (100)   int main(int argc, char* argv[]) {     ……
大神 你怎么回答这么水的问题啊 你应该多提供一些nb的知识给大家的
[其他解释]

#include <iostream>

using namespace std;

void main()
{
char a[100];
char b('c');
int c[3]={0,0,0};
cin>>a;
int length=strlen(a);
for(int i=0;i<length;++i)
{
if(a[i]!=b)
{
int index=a[i]=='a'?0:(a[i]=='b'?1:2);
c[index]++;
}
b=a[i];
}
printf("a:%d\nb:%d\nc:%d\n",c[0],c[1],c[2]);
system("pause");
}

热点排行