My Simple Java Solution without using lastIndexOf()


  • 0
    M
        public int lengthOfLastWord(String s) {
            if (s == null || s.length() == 0) return 0;
            int n = s.length();
            int lastWord = n;
            for (int i=n - 1; i>=0; --i) {
                if (s.charAt(i) != ' ') {
                    lastWord = i;
                    break;
                }
            }
            if (lastWord == n) return 0;
            
            int lastSpace = -1;
            for (int i=0; i<lastWord; ++i) {
                if (s.charAt(i) == ' ') {
                    lastSpace = i;
                }
            }
            return lastWord - lastSpace;
        }
    

Log in to reply
 

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