[LeetCode] Length of Last Word
Well, the basic idea is very simple. Start from the tail of s
and move backwards to find the first non-space character. Then from this character, move backwards and count the number of non-space characters until we pass over the head of s
or meet a space character. The count will then be the length of the last word.
1 class Solution { 2 public: 3 int lengthOfLastWord(string s) { 4 int len = 0, tail = s.length() - 1; 5 while (tail >= 0 && s[tail] == ' ') tail--; 6 while (tail >= 0 && s[tail] != ' ') { 7 len++; 8 tail--; 9 } 10 return len; 11 } 12 };
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步