题目要求找出句子中最长的单词,是一个典型的字符串处理问题。
总时间限制: 1000ms 内存限制: 65536kB
输入一个英文句子,长度不超过40个字符。编写程序,输出句子中最长的一个单词。
1.输入只有一个句子,不需使用while
2.若句尾有标点,则标点和最后一个单词可看成是一个单词,可以不用作额外判断
3.假设句中最长的单词只有一个
长度不超过40的字符串
句中最长的单词
This is a test sentence
sentence
由于符号也被算作单词,并且我们不知道都有哪些符号,所以只能通过判断是否为空格和结束符来确定一个单词的长度。最后比较大小输出最长的单词。
#include <iostream>
using namespace std;
int main() {
char cstr[41];
cin.getline(cstr, 41);
int idx = 0, mlen = 0, mIdx = 0;
while (cstr[idx] != '\0') {
if (cstr[idx] == ' ') {
idx++;
continue;
}
int len = 0, lidx;
if (cstr[idx] != ' ') {
lidx = idx;
while (cstr[idx] != ' ') {
len++;
if (cstr[idx] == '\0') break;
idx++;
}
}
if (len > mlen) {
mlen = len;
mIdx = lidx;
}
}
char res[41];
for (idx = 0; idx < mlen; ++idx) {
res[idx] = cstr[mIdx + idx];
}
res[idx] = '\0';
cout << res << endl;
return 0;
}
2880.cpp 代码长度:563B 内存:128kB 时间:1ms 通过率:95% 最小内存:128kB 最短时间:0ms
带有空格的字符串需要通过cin.getline来获取,之后分别设置标志记录单词的起始下标和长度,通过空格和'\0'来判断单词结尾,并比较单词长度最后输出。
有任何的改进意见欢迎大家在微信平台公众号主页面留言或者发表issue。