Efficient solution in Java


  • 0
    R
    public class Solution {
        public int lengthOfLastWord(String s) {
            if(s==null || s.isEmpty() ) return 0;
            int c = 0;
            
            for(int i=s.length()-1; i>=0; i--){
                if(s.charAt(i) != ' ') c++;
                else if(c>0) break;
            }
            
            return c;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.