首页 > 学院 > 开发设计 > 正文

54:Length of Last Word

2019-11-06 08:50:53
字体:
来源:转载
供稿:网友

题目: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; }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表