Given a string s consists of upper/lower-case alphabets and empty space characters
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 =
return
' ', 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.
A:
先用 j 指向第一个字母(从后向前) , 再用i指向第一个非字母(也是从后向前)
public class Solution {
public int lengthOfLastWord(String s) {
if(s == null || s.length() == 0){return 0;};
int i,j; // i is the start point, while j is the end point of a word
j = s.length()-1;
while(j>=0){
if(s.charAt(j) ==' '){
j--;
}else{
break;
}
}
//run from j
i = j;
while(i>=0){
char ch = s.charAt(i);
boolean isUpper = ( ch>='A' && ch<='Z');
boolean isLower = ( ch>='a' && ch<='z');
if( isUpper || isLower ){
i--;
}else{
break;
}
}
return j-i;
}
}
Mistakes:
对于要考虑边界的,一个好 习惯就是先把 最最边界的情况列出来,单独处理。 例如,这道题目。 因为要用到index,那么s.length() == 0的时候,显然不能有index, 所以,我们单独处理这个。所以加了句
----------------第二遍----------------------- 思路同上------------
public class Solution {
public int lengthOfLastWord(String s) {
s= s.toLowerCase();
int end = s.length()-1;
// point end to the first alphabet
while(end>=0 && !( s.charAt(end) >='a' && s.charAt(end) <='z')){
end--;
}
int begin = end;
while(begin>=0&& s.charAt(begin) >='a' && s.charAt(begin) <='z' ){
begin--;
}
return end-begin;
}
}
-----------------------------3 rd Pass -----------------------
public class Solution {
public int lengthOfLastWord(String s) {
s = s.trim();
int i= s.lastIndexOf(" ");
return i<0?s.length(): s.length()-1-i;
}
}
No comments:
Post a Comment