首页 > 代码库 > Leetcode: Length of Last Word

Leetcode: Length of Last Word

许多次通过,主要是没有考虑到这种情况:“A  C    ”结尾有多重空格的情况。

 1 public class Solution {
 2     public int lengthOfLastWord(String s) {
 3         int j, k;
 4         if(s == null) return 0;
 5         //if(!s.contains(‘ ‘)) return s.length();
 6         int lastspace = s.lastIndexOf(‘ ‘);
 7         if(lastspace == s.length()-1){
 8             for(k=s.length()-2; k>=0; k--){
 9                 if(s.charAt(k)!=‘ ‘) break;
10             }
11             for(j=k; j>=0; j--){
12                 if(s.charAt(j)==‘ ‘) break;
13             }
14             return k-j;
15         }
16         return s.length()-lastspace-1;
17     }
18 }

别人的solution:

Solution 1: 非常简洁,用split()函数

1 public class Solution {
2     public int lengthOfLastWord(String s) {
3         // Start typing your Java solution below
4         // DO NOT write main() function
5             String[] words = s.split(" ");
6             return words.length==0?0:words[words.length-1].length();
7     }
8 }

Solution 2: 

 1 public class LengthOfLastWord {
 2     public int lengthOfLastWord(String s) {
 3         if (s.length() == 0) {
 4             return 0;
 5         }
 6         int length = 0;
 7         boolean wordStart = false;
 8         int i = s.length() - 1;
 9         while (i >= 0) {
10             if (s.charAt(i) != ‘ ‘ && wordStart == false) {
11                 length++;
12                 wordStart = true;
13             } else if (wordStart == true && s.charAt(i) != ‘ ‘) {
14                 length++;
15             }
16 
17             else if (wordStart == true && s.charAt(i) == ‘ ‘) {
18                 break;
19             }
20             i--;
21         }
22         return length;
23     }
24 }