[关闭]
@PaulGuan 2016-10-02T10:09:37.000000Z 字数 585 阅读 667

B - Lucky Substring 题解

Algorithm


此处输入链接的描述

题目大意

一个可以有前导0的长度n (1<=n<=50) 的只带数字的字符串,判断其出现次数最多的幸运数字(只由4和7组成),出现次数相同就按字典序排序,输出出现次数最多的幸运数,如果没有包含幸运数字,输出-1。

分析

虽然本题要求找出次数最多的幸运数字,但是,其实只用找4和7,因为其他的多位数幸运数字都包含4和7这两个幸运数字,例如出现了一次47477,那么出现了2次4和3次7,而且,多位数的幸运数字的字典序是大于4和7的,所以,输出只可能是在4,7和-1中的一个。

代码

  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <algorithm>
  5. using namespace std;
  6. string a;
  7. int main(void)
  8. {
  9. cin>>a;
  10. int c4=0,c7=0;
  11. int i;
  12. for(i=0;i<a.size();i++)
  13. {
  14. if(a[i]=='4')
  15. c4++;
  16. if(a[i]=='7')
  17. c7++;
  18. }
  19. if(c4>c7)
  20. cout<<"4"<<endl;
  21. else if(c4<c7)
  22. cout<<"7"<<endl;
  23. else if(c4==c7&&c4!=0)
  24. cout<<"4"<<endl;
  25. else
  26. cout<<"-1"<<endl;
  27. return 0;
  28. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注