LeetCode:Length of Last Word
2014-05-11 19:19
357 查看
题目链接
Given a string s consists of upper/lower-case alphabets and empty space characters
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 =
return
借助strlen函数,相当于遍历两遍字符串 本文地址
遍历一遍字符串
【版权声明】转载请注明出处:/article/4879741.html
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函数,相当于遍历两遍字符串 本文地址
class Solution { public: int lengthOfLastWord(const char *s) { if(s == NULL)return 0; int len = strlen(s), i, res = 0; for(i = len-1; i >= 0 && s[i] == ' '; i--);//从尾部开始找到第一个非空格字符 for(; i >= 0 && s[i] != ' '; i--)res++; return res; } };
遍历一遍字符串
class Solution { public: int lengthOfLastWord(const char *s) { if(s == NULL)return 0; int res = 0, cnt = 0; for(; *s != '\0'; s++) { if(*s == ' ') { if(cnt != 0) res = cnt; cnt = 0; } else cnt++; } return cnt == 0 ? res : cnt; } };
【版权声明】转载请注明出处:/article/4879741.html
相关文章推荐
- LeetCode 58 Length of Last Word
- Leetcode 58 Length of Last Word
- leetcode笔记--Length of Last Word
- 【leetcode】:Length of the LastWord
- Leetcode Length of Last Word
- LeetCode - Length of Last Word
- [LeetCode]Length Of Last Word
- LeetCode(48)-Length of Last Word
- Leetcode Length of Last Word
- LeetCode_Length of Last Word
- 【Leetcode】【python】Length of Last Word
- 《leetCode》:Length of Last Word
- LeetCode_58---Length of Last Word
- LeetCode 058 Length of Last Word
- leetcode 58: Length of Last Word
- <LeetCode><Easy> 58 Length of Last Word
- LeetCode—Length of Last Word
- leetcode-58-Length of Last Word
- leetcode:Length of Last Word
- 【Leetcode】Length of Last Word JAVA