C++基础练习题(一): 查找最短单词
生活随笔
收集整理的這篇文章主要介紹了
C++基础练习题(一): 查找最短单词
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
/*<說明>
編程實現將字符串中最短的單詞輸出,在主函數中輸入字符串,編寫一個函數完成最短單詞的查找
</說明>*/
#include<time.h>
#include<iostream>
using namespace std;void shortestWord(char* in)
{int i,j=0;int o[1000];for(i=0;*(in+i)!=0;i++){if(*(in+i)==' '){o[j]=i; //o的作用是定位每一個空格的位置 通過空格位置間隔的大小判斷單詞的長短j++;}}j--;int z=0;int k=o[0]; //k是最短單詞的個數 初始化為第一個空格的位置 因為后面的操作沒有考慮第一個int l[50];for(;j!=0;j--){ if(o[j]-o[j-1]-1<k){z=0;k=o[j]-o[j-1]-1;l[0]=j-1;}else if(o[j]-o[j-1]-1==k){z++; //z統計有多少個最短單詞l[z]=j-1;}}if(o[0]==k){for(int n=0;n<k;n++){printf("%c",*(in+n)); //如果第一個單詞就是最短的 打印
}printf(" ");}for(int m=z;m>0;m--){for(int n=1;n<=k;n++){printf("%c",*(in+o[l[m]]+n)); //打印其他最短單詞
}printf(" ");}
}
void main()
{char in[1000]="Learning a the parameters of neural networks is perhaps one of the most well studied problems within the field of machine learning. Early work on backpropagation algorithms showed that the gradient of the neural net learning objective could be computed efficiently and used within a gradient descent scheme to learn the weights of a network with multiple layers of non-linear hidden units. Unfortunately, this technique doesn’t seem to generalize well to networks that have very many hidden layers (i.e. deep networks). The common experience is that gradient-descent progresses extremely slowly on deep nets, seeming to halt altogether before making significant progress, resulting in poor performance on the training a set (under-fitting)";int a=clock();shortestWord(in);int b=clock();int c=b-a;printf("%d",c);getchar();
}
上面是自己寫的代碼 效果并不好 測試了一下運行效果2毫秒 太慢 而且沒有考慮有連續空格的情況。
/*<書上答案>*/ #include<iostream> #include<time.h> using namespace std; const int Max=200; char *findshort(char s[]) {static char s1[Max]; //其地址要返回,所以設計為靜態變量char s2[Max];int i=0,j,len1=0,len2=0;while(s[i++]!='\0');s[i-1]=' ';s[i]='\0';i=0;while(s[i]!='\0'){if(s[i]==' '&&s[i+1]!='\0'&&s[i+1]==' ') //跳過多余空格 {i++;continue;}if(s[i]!=' ') //提取一個單詞到S2中 {s2[len2++]=s[i];}else if(len1==0){len1=0;for(j=0;j<len2;j++) //將S2復制到S1中s1[len1++]=s2[j];s1[len1]='\0';len2=0;}else if(len1>len2){len1=0;for(j=0;j<len2;j++) //將S2復制到S1中s1[len1++]=s2[j];s1[len1]='\0';len2=0;}else{len2=0;}i++;}return s1; } void main() {char s[Max]="asddddd gg las sdlgaw va eg aoeng a ge a e gae geoia ae x eox ge x ieg ns e a dfge qdn i am ver";cout<<"輸入單詞串:";int a=clock();cout<<"最短單詞:"<<findshort(s)<<endl;int b=clock();int c=b-a;cout<<c<<endl;getchar(); }這是答案中的 只打印了第一個最短單詞 但是實現比自己寫的代碼快很多。
總結
以上是生活随笔為你收集整理的C++基础练习题(一): 查找最短单词的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android系统架构图及简单的系统架构
- 下一篇: 引用借以记录借鉴 实现记住密码和自动登录