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;
}
}
方法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;
}
}
相关文章推荐
- Leetcode Length of Last Word
- leetcode— Length of Last Word
- leetcode 21: Length of Last Word
- LeetCode_Length Of Last Word
- leetcode58:Length of last word
- Leetcode#58 Length of Last Word
- Length of Last Word
- Length of Last Word
- 58 Length of Last Word
- 60 leetcode - Length of Last Word
- Day5 Length of Last Word
- lintcode-easy-Length of Last Word
- LeetCode-Length of Last Word
- Length of Last Word
- 【LeetCode】58 - Length of Last Word
- Length of Last Word 最后一个单词的长度
- LeetCode Length of Last Word
- [LeetCode]Length of Last Word
- Length of Last Word
- Leetcode 细节实现 Length of Last Word