题目:Given a string s consists of upper/lower-case alphabets and empty space characters ’ ‘, return the length of last Word in the string. If the last word does not exist, return 0. Note: A word is defined as a character sequence consist
解题代码一(从后往前扫描):
// 逆序扫描// 时间复杂度 O(n),空间复杂度 O(1)class Solution {public: int lengthOfLastWord(string s) { int len = 0; int i = s.size() - 1; while (i >= 0) if (s[i] == ' ') --i; else break; while (i >= 0) if (s[i] != ' ') ++len, --i; else break; return len; }};解题代码二(从前往后扫描):
// 顺序扫描,记录每个 word 的长度// 时间复杂度 O(n),空间复杂度 O(1)class Solution {public: int lengthOfLastWord(const string& s) { int len = 0; for (int i = 0; i < s.size(); ) { if (s[i] != ' ') ++len, ++i; else { ++i; if (i < s.size() && s[i] != ' ') ++len; } } return len; }};新闻热点
疑难解答