422. Length of Last Word【LintCode java】

Description

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.

A word is defined as a character sequence consists of non-space characters only.

Example

Given s = "Hello World", return 5.

解题:返回最后一个单词,注意是要用一个变量缓冲一下,否则一个字符串的最后几个字符为空时,可能会丢失数据。代码如下:

public class Solution {
/**
* @param s: A string
* @return: the length of last word
*/
public int lengthOfLastWord(String s) {
// write your code here
int count = 0;
int res = 0;
for(int i = 0; i < s.length(); i++){
if( Character.isLetter(s.charAt(i)) ){
count++;
}else {
res = count;
count = 0;
}
}
if(count != 0)
return count;
else
return res;
}
}
上一篇:Python TVTK 标量数据可视化与矢量数据可视化,空间轮廓线可视化


下一篇:10.彻底理解ReentrantLock