牛客华为机试题刷题笔记(一)

马上华为提前批开始了,吓得我赶紧上牛客网刷题,记录如下:
所有代码都在github

1.字符串最后一个单词的长度

一段英文字符串中最后一个单词的长度。
题目比较简单,做法有很多:
比如,
可以放到stringstream里面split,拿到最后一个单词
也可以从后往前数到第一个空格为止。

让我觉得麻烦是第一次做这种要自己写输入的题,
C++用cin是遇到空格停止的,因此要用getline读入一行

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string str;
    getline(cin,str);
    int i=str.size()-1;
    int count=0;
    while(str[i]!=' '&&i>=0)
    {
    ++count;
    --i;
    }
    cout<<count<<endl;
    return 0;
}

2.计算字符个数

输入一个字符串和一个字符,统计该字符在该字符串中出现的次数。
for循环比较即可,没什么好说的

#include <iostream>
#include <string>
using namespace std;
int main(int argc,char **argv)
{
    string str;
    char c;

    getline(cin,str);
    cin>>c;

    int count=0;
    for(int i=0;i<str.size();++i)
    {
    if(tolower(str[i])==tolower(c))
        ++count;
    }
    cout << count<<endl;


    return 0;
}

3.明明的随机数

说是随机数,其实跟随机数没有半毛钱关系,
就是输入一串整数,整数去重,输出排好序的结果,
C++使用std::sortstd::uniquevector::erase可以轻易做到

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
using namespace std;


int main()
{
    // input 
    int n;
    while(cin>>n)
    {
    vector<int>v;
    v.reserve(1024);
    int j;
    for(int 
  • 9
    点赞
  • 76
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值