您的位置:首页 > 其它

3.15 Length of Last Word

2014-07-10 01:08 323 查看
这道题很简单。一次完成。

方法I:

public class Solution {
//1st: this looks simple
public int lengthOfLastWord(String s) {
s = s.trim();
if(!s.contains(" ")) return s.length();
String[] arr = s.split(" ");
int len = arr.length;
if(len == 1) return 0;
else return arr[len-1].length();
}
}
方法II:

ublic class Solution {
//2nd: in case there are multiple spaces attached to the last word,e.g. "hello word "
//read s from the end
//afer reading http://tianrunhe.wordpress.com/2012/07/26/length-of-last-word/ public int lengthOfLastWord(String s) {
int length = 0;
int i = s.length() - 1;
while(i>=0 && (s.charAt(i) == ' ')){
i--;
}
while((i>=0) && (s.charAt(i) != ' ')) {
length++;
i--;
}
return length;
}
}

方法III:
public class Solution {
public int lengthOfLastWord(String s) {
s = s.trim();
if(!s.contains(" ")) return s.length();//After trimming, " ab", "ab " will be "ab", so simply return length.
for(int i = s.length()-1; i>=0; i--){
if(s.charAt(i) == ' '){
return s.length()-1-i;
}
}
return 0;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: