《leetCode》:Length of Last Word
来源:互联网 发布:模拟退火 遗传算法结合 编辑:程序博客网 时间:2024/05/22 10:50
题目
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.
思路
此题利用java来做将相当简单,利用空格将String进行拆分,然后检查最后一个字符子串的长度即可;有一点需要注意的是这种测试样例(全有空格构成的):s=” “;
public class Solution { public int lengthOfLastWord(String s) { if(s==null){ return 0; } String []arrStr=s.split(" "); // System.out.println(arrStr[arrStr.length-1]); return arrStr.length>0?arrStr[arrStr.length-1].length():0; }}
出现的问题
1、没有考虑全是空格的测试用例:s=” “;
解决方法:加一个判断即可。
最后的AC结果即可如下:
但是,我相信这不是这个题的初衷,因此还准备用C语言来实现下。
思路:找到最后一个单词的起点和终点即可。
实现代码如下:
int lengthOfLastWord(char* s) { if(s==NULL){ return 0; } puts(s); int len=strlen(s); if(len<1){ return 0; } int pos=-1; //先找到最后一个word的终点。 for(int i=len-1;i>=0;i--){ if(s[i]!=32){//32是空格字符的ASCII码 pos=i; break; } } if(pos==-1)//没有单词 return 0; int count=0; for(int i=pos;i>=0;i--){ if(s[i]==32){//碰到了倒数第一个空格,就退出 break; } count++; } return count; }
AC结果如下:可以看出Runtime为0ms,别用java来写要快。但是在和别人提交的代码中,效率并不好。
1 0
- 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]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] 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 | Length of Last Word
- LeetCode - Length of Last Word
- Leetcode: Length of Last Word
- JVM内存分配
- UTF-8 和 GBK 的 NSString 相互转化的方法
- Objective-C中的 id, isa,和 instancetype
- Android高级之xUtils框架(三)BitmapUtils
- Cpp--const限定符
- 《leetCode》:Length of Last Word
- PostgreSQL学习手册(模式Schema)
- Qt中丰富的容器类---数组QVector、链表QLinkedList、映射表QMap、哈希表QHash
- 字典 不可变字典NSDictionary 可变字典NSMutableDictionary
- javascript中的 offsetParent
- 使用github托管代码
- android 很多牛群叉界面库github地址
- PostgreSQL学习手册(表的继承和分区)
- OC-Block和数组高级