题目:
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
.
链接: http://leetcode.com/problems/length-of-last-word/
题解:
从后向前遍历。
Time Complexity - O(n), Space Complexity - O(1)。
public class Solution {
public int lengthOfLastWord(String s) {
if(s == null || s.length() == 0)
return 0;
int i = s.length() - 1, count = 0;
s = s.toLowerCase(); while(i >= 0 && (s.charAt(i) > 'z' || s.charAt(i) < 'a') )
i --; while(i >= 0 && s.charAt(i) != ' '){
count ++;
i --;
} return count;
}
}
Update:
看一看以前的代码...完全不认识了...
public class Solution {
public int lengthOfLastWord(String s) {
int count = 0;
if(s == null || s.length() == 0)
return count; for(int i = s.length() - 1; i >= 0; i--) {
if(s.charAt(i) == ' ') {
if(count == 0)
continue;
else
break;
}
count++;
} return count;
}
}
二刷:
还是跟一刷一样,从后向前遍历。
Java:
Time Complexity - O(n), Space Complexity - O(1)。
public class Solution {
public int lengthOfLastWord(String s) {
if (s == null || s.length() == 0) {
return 0;
}
int count = 0;
for (int i = s.length() - 1; i >= 0; i--) {
if (s.charAt(i) != ' ') {
count++;
} else if (count > 0) {
break;
}
}
return count;
}
}
三刷:
这道题属于基本很少能给人留下印象的题。从后向前遍历, 假如s.charAt(i)不为空格的时候,我们增加count, 否则,假如count = 0,我们还没找到单词,继续查找。 假如count > 0,说明我们已经找到并且计算了最后一个单词,返回count。 遍历数组以后也返回count,因为有可能字符串里就一个单词,没空格。 这分析写得比较糙...
Java:
Time Complexity - O(n), Space Complexity - O(1)。
public class Solution {
public int lengthOfLastWord(String s) {
if (s == null) {
return 0;
}
int count = 0;
for (int i = s.length() - 1; i >= 0; i--) {
if (s.charAt(i) != ' ') {
count++;
} else if (count > 0) {
return count;
}
}
return count;
}
}