一、题目叙述:
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
.
Subscribe to see which companies asked this question.
二、解题思路:
easy题,但注意考虑全面!整体思路就是倒着遍历数组,找到第一个非空格单词位置,然后从这个位置继续向前遍历并累加,直到碰到空格停止。
三、源码:
import java.util.ArrayList;
import java.util.List;
public class Solution
{
public int lengthOfLastWord(String s)
{
char[] res = s.toCharArray();
int n = res.length;
int count = 0;
int start = n - 1;
for (int i = n - 1; i >= 0; i--)
{
if (res[i] == ' ') continue;
else {start = i; break; }
}
for (int i = start; i >= 0; i--)
{
if (res[i] == ' ') break;
else count++;
}
return count;
}
public static void main(String args[])
{
// int[] digits = {0};
Solution solution = new Solution();
String s = "hello world ";
// int[][] abc = {{2,5},{8,4}};
// int[] b = {2,3,4};
// for(int i = 0; i < abc.length; i ++)
System.out.print(solution.lengthOfLastWord(s));
}
}