LeetCode:Length of Last Word

简介:

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 consists of non-space characters only.

For example, 
Given s = "Hello World",
return 5.


 

借助strlen函数,相当于遍历两遍字符串                       本文地址

复制代码
 1 class Solution {
 2 public:
 3     int lengthOfLastWord(const char *s) {
 4         if(s == NULL)return 0;
 5         int len = strlen(s), i, res = 0;
 6         for(i = len-1; i >= 0 && s[i] == ' '; i--);//从尾部开始找到第一个非空格字符
 7         for(; i >= 0 && s[i] != ' '; i--)res++;
 8         return res;
 9     }
10 };
复制代码

遍历一遍字符串

复制代码
 1 class Solution {
 2 public:
 3     int lengthOfLastWord(const char *s) {
 4         if(s == NULL)return 0;
 5         int res = 0, cnt = 0;
 6         for(; *s != '\0'; s++)
 7         {
 8             if(*s == ' ')
 9             {
10                 if(cnt != 0)
11                     res = cnt;
12                 cnt = 0;
13             }
14             else cnt++;
15         }
16         return cnt == 0 ? res : cnt;
17     }
18 };
复制代码





本文转自tenos博客园博客,原文链接:http://www.cnblogs.com/TenosDoIt/p/3722115.html,如需转载请自行联系原作者

目录
相关文章
LeetCode contest 187 1437. 是否所有 1 都至少相隔 k 个元素 Check If All 1's Are at Least Length K Places Away
LeetCode contest 187 1437. 是否所有 1 都至少相隔 k 个元素 Check If All 1's Are at Least Length K Places Away
LeetCode 318. Maximum Product of Word Lengths
给定一个字符串数组 words,找到 length(word[i]) * length(word[j]) 的最大值,并且这两个单词不含有公共字母。你可以认为每个单词只包含小写字母。如果不存在这样的两个单词,返回 0。
62 0
LeetCode 318. Maximum Product of Word Lengths
LeetCode 290. Word Pattern
给定一种 pattern(模式) 和一个字符串 str ,判断 str 是否遵循相同的模式。 这里的遵循指完全匹配,例如, pattern 里的每个字母和字符串 str 中的每个非空单词之间存在着双向连接的对应模式。
35 0
LeetCode 290. Word Pattern
LeetCode 212. Word Search II
给定一个二维网格 board 和一个字典中的单词列表 words,找出所有同时在二维网格和字典中出现的单词。 单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母在一个单词中不允许被重复使用。
61 0
LeetCode 212. Word Search II
|
索引
LeetCode 79. Word Search
给定一个2D板和一个单词,找出该单词是否存在于网格中。 该单词可以由顺序相邻的单元的字母构成,其中“相邻”单元是水平或垂直相邻的单元。 相同的字母单元格不得多次使用。
54 0
LeetCode 79. Word Search
LeetCode contest 190 5417. 定长子串中元音的最大数目 Maximum Number of Vowels in a Substring of Given Length
LeetCode contest 190 5417. 定长子串中元音的最大数目 Maximum Number of Vowels in a Substring of Given Length
|
数据库
LeetCode(数据库)- First and Last Call On the Same Day
LeetCode(数据库)- First and Last Call On the Same Day
89 0
LeetCode 58 Length of Last Word(最后单词的长度)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50592917 翻译 给定一个包含大小写字母和空格字符的字符串, 返回该字符串中最后一个单词的长度。
714 0
|
21天前
|
算法 C++
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题-2
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题
|
21天前
|
算法 C++
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题-1
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题