题目
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来写要快。但是在和别人提交的代码中,效率并不好。