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.
方法二:
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.
Hide Tags: String
题意: 记录字符创最后一个单词的长度,如果最后一个单词不存在,返回0
解题思路:
方法一:
刚开始这道题想的太简单了,首先最开始的想法是得知s的长度,然后从头开始遍历找到最后一个空格的位置,作减法就可以得到最后单词的长度
然而忽略了,如果这个字符串结尾有空格的情况。如“a ”。于是改变思路,从后面开始遍历,找到最后一个单词的最后一个字符开始计数,然后依次向前知道遇到第一个空格。
方法二:
使用投机取巧的方法,用split函数把字符串按照空格分隔好,返回最后那个就行。。。
代码如下:
方法一:
public static int lengthofLastWord(String s)
{
if(s==null||s.length()==0)
{
return 0;
}
else
{
int count=0;
//从字符串尾部开始遍历
for (int i = s.length()-1; i >0; i--)
{
char temp=s.charAt(i);
if (count==0)
{
if(temp!=' ')
{
//如果非空,计数+1
count++;
}
if(temp==' ')
{
//如果空,继续遍历
continue;
}
}
else
{
//一个单词记录完后,如遇空格,遍历中断
if (temp==' ')
{
break;
}
//如果一个单词未记录完,继续遍历
else
{
count++;
}
}
}
return count;
}
方法二:
public static int lengthofLastWord1(String s)
{
//抽出字符串中的空格,然后将每个单词存放到String数组中
String []a=s.split(" ");
if (a==null||a.length==0)
{
return 0;
}
else
{
//直接返回String数组中最后一个单词的长度即可
int output=a[a.length-1].length();
return output;
}
}