Simple Java Solution in O(n)


  • -2
    A
    public class Solution {
        public int lengthOfLastWord(String s) {
            if (s == null || s.isEmpty()){
                return 0;
            }
            s = s.trim();
            int count = 0;
            for (int i = s.length() - 1; i >= 0 ;i--){
                if (s.charAt(i) == ' '){
                    break;
                }
                count++;
            }
            return count;
        }
    }

Log in to reply
 

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