[leetcode]Length of Last Word (求最后一个单词的长度 C语言实现)
来源:互联网 发布:惠泽了知福建版 编辑:程序博客网 时间:2024/04/28 18:20
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.
题意:求取字符串中最后一个单词的长度,若不存在则返回0,字符串中只包括空格和单词
解题思路:
解题思路:求最后一个单词的长度,一个字符串包括单词和空格,
所以我们需要去除字符串最后的空格和字符串开始的空格,对字符串查询函数
字符串查询函数strrchr(const char *s, char ch)查询s字符串中最后一次出现ch字符的位置,并返回其位置
C语言实现代码:
/** * 解题思路:求最后一个单词的长度,一个字符串包括单词和空格, * 所以我们需要去除字符串最后的空格和字符串开始的空格,对字符串查询函数 * 字符串查询函数strrchr(const char *s, char ch)查询s字符串中最后一次出现ch字符的位置,并返回其位置 */int lengthOfLastWord(char *s) { int i, j; char *str, *p; p = NULL; if(s == NULL) return 0; i = 0; while(*(s + i) != '\0'){//获取字符串的长度 i++; } while(*(s+i-1) == 32){//判断字符串最后面有没有空格,ASCII码32代表空格,若有空格长度减一 i--; } j = 0; while(*(s+j) == 32){//判断字符串前面有没有空格,若有j+1 j++; } if(i <= j) return 0;//若i<=j表示字符串全由空格组成,没有单词 str = (char *)malloc((i+1)*sizeof(char)); memset(str, 0, sizeof(str));//把不包括前后空格的字符串复制给str strncpy(str, s+j, i-j); p = strrchr(str, 32);//从后开始 if(p == NULL){ return i-j; }else { return (str+i-j-1) - p; }}
0 0
- [leetcode]Length of Last Word (求最后一个单词的长度 C语言实现)
- leetcode 58. Length of Last Word(C语言,计算最后一个单词的长度)19
- LeetCode Length of Last Word最后一个单词的长度
- leetcode:Length of Last Word最后一个单词的长度
- [LeetCode] Length of Last Word - 最后一个单词的长度
- LeetCode Length of Last Word(最后一个单词的长度)
- (LeetCode)Length of Last Word --- 最后一个单词的长度
- LeetCode OJ 之 Length of Last Word(求最后一个单词的长度)
- leetcode 58.Length of Last Word-最后一个单词长度
- Length of Last Word 最后一个单词的长度
- Length of Last Word 最后一个单词的长度
- Length of Last Word (最后一个单词的长度) 【leetcode】
- Length of Last Word 字符串中最后一个单词的长度 @LeetCode
- 【LeetCode】- Length of Last Word(最后一个单词的长度)
- LeetCode | Length of Last Word(最后一个单词的长度)
- LeetCode 58. Length of Last Word(最后一个单词的长度)
- LeetCode------58. Length of Last Word(字符串中最后一个单词的长度)
- Leetcode刷题记——58. Length of Last Word(最后一个单词的长度)
- 程序中呼叫Class(类)
- LayoutInflater、View的绘制流程、自定义View、Invalidate和postInvalidate的区别
- [省选前题目整理][BZOJ 1059][ZJOI 2007]矩阵游戏(二分图最大匹配)
- HDFS的重要参数配置<一> JVM的配置
- A8U推一键上面洗车APP软件
- [leetcode]Length of Last Word (求最后一个单词的长度 C语言实现)
- U-Boot启动过程完全分析
- ProtoBuf开发者指南
- 每天linux命令_chmod
- 问题总结
- 开发证书和发布证书的配置(图解篇)
- 麦肯锡评12大颠覆性技术
- linux mmseg3分词使用
- Kali下安装Oracle JDK