题解|HJ1 字符串最后一个单词的长度
字符串最后一个单词的长度
https://www.nowcoder.com/practice/8c949ea5f36f422594b306a2300315da?tpId=37&&tqId=21224&rp=1&ru=/ta/huawei&qru=/ta/huawei/question-ranking
题意:计算字符串最后一个单词的长度,单词以空格隔开,字符串长度小于5000。 (注:字符串末尾不以空格为结尾)
方法一:维护当前单词长度
在输入句子时,由于使用scanf("%s",str)会将空格分割的字符串自动划分,变量str会不断更新为最新的一个不包含空格的字符序列。所以可以维护一个变量len,利用EOF判断字符串输入结束,同时不断更新当前单词长度。这样当读到文件末尾,当前的len即为最后一个单词的长度。 时间复杂度:,空间复杂度:
#include <stdio.h>
#include <string.h>
int main() {
char str[5005];
int len = 0;
while (scanf("%s", str) != EOF) {
len = strlen(str);
}
printf("%d\n", len);
return 0;
}
方法二:维护最后一个空格的位置
当使用 getline(cin,str); 输入字符串时,string中可以包含空格。此时可以用str.find()查找每个空格的位置并存放在一个栈里。使用整个字符串的长度减去最后一个空格所在的位置再-1,就是最后一个单词的长度。 时间复杂度:,空间复杂度:
#include<iostream>
#include<cstring>
#include<stack>
using namespace std;
int main() {
string str;
getline(cin,str);
int pos=0;
stack<int>st;
while(str.find(' ',pos)!=string::npos){
pos=str.find(' ',pos);
st.push(pos);
pos++;
}
if(st.empty()) {
cout<< str.size() << endl;
} else {
cout<< str.size() - st.top() - 1 << endl;
}
return 0;
}