题解 | #字符串最后一个单词的长度#
字符串最后一个单词的长度
https://www.nowcoder.com/practice/8c949ea5f36f422594b306a2300315da
#include <iostream>
using namespace std;
int main() {
string input;
while (getline(cin, input)) { // 注意 while 处理多个 case
int length = 0;
// for(auto c = input.rbegin(); c!=input.rend(); c++){
// if(*c == ' '){
// break;
// }
// length++;
// }
int i = input.size()-1;
// 先跳过结尾可能存在的空格
while(i>=0 && input[i]==' '){
i--;
}
while(i>=0 && input[i]!=' '){
i--;
length++;
}
cout << length << endl;
}
}
// 64 位输出请用 printf("%lld")
查看7道真题和解析
