题解 | #统计字符#
字符串最后一个单词的长度
http://www.nowcoder.com/practice/8c949ea5f36f422594b306a2300315da
#include <iostream>
#include <string>
class Solution {
private:
static bool isSep(int ch) {
return ch == '\r' || ch == '\n' || ch=='\t' || ch == ' ';
}
static std::string getWord(const std::string s, size_t len, size_t &i) {
std::string word = "";
int ch = 0;
// 跳过空白
for (; i < len && (ch = s.at(i)); i++) {
if (!isSep(ch)) {
break;
}
}
for (; i < len && (ch = s.at(i)); i++) {
if (isSep(ch)) {
break;
}
word.append(1, ch);
}
return word;
}
public:
size_t lenOfLastWord(const std::string s) {
std::string thisWord, lastWord = "";
size_t len = s.size();
for(size_t i = 0; ;lastWord = thisWord) {
thisWord = getWord(s, len, i);
if (thisWord.size() < 1) {
break;
}
}
return lastWord.length();
}
};
int main(int argc, char *argv[]) {
std::string s;
std::getline(std::cin, s);
Solution solution;
std::cout << solution.lenOfLastWord(s) << std::endl;
return 0;
}
CVTE公司福利 691人发布
查看26道真题和解析