BiruLyu
5/23/2017 - 7:18 PM

58. Length of Last Word.java

class Solution(object):
    def lengthOfLastWord(self, s):
        """
        :type s: str
        :rtype: int
        """
        
        lengthLast = 0;
         
        for i in range(len(s)-1,-1,-1):
            if s[i] == ' ' and lengthLast == 0:
                continue;
            if s[i] == ' ':
                break;
            lengthLast += 1;
       
        return lengthLast;
"""
TESTCASES:

Input:
""
"Hello World"
"Hello"
"Hello World we"
"a "
"a aa "
"a aaa                  "

Output:
0
5
5
2
1
2
3

"""
            
            
        
public class Solution {
    public int lengthOfLastWord(String s) {
    
        int res = 0;
    
        s = s.trim();
        if(s == "") return res;
        for(int i = s.length() - 1; i >= 0; i--){
            if(s.charAt(i) == ' '){
                res = s.length() - i - 1;
                break;
            }
        }
        
        return res == 0 ? s.length() : res;
    }
}

/*
Input:
""
"Hello World "
"World"
"World "
"b   a    "

Output:
0
5
5
5
1
*/