My Java Solution


  • 0
    A
    public class Solution {
        public int lengthOfLastWord(String s) {
            int idx = s.length() - 1;
            
            while (idx >= 0 && s.charAt(idx) == ' ') {
                idx--;
            }
            
            if (idx < 0) {
                return 0;
            }
            int cnt = 0;
            while (idx >= 0 && s.charAt(idx) != ' ') {
                cnt++;
                idx--;
            }
            
            return cnt;
        }
    }

  • 0
    S

    Same code for reference

    public class Solution {
        public int lengthOfLastWord(String s) {
            int i = s.length()-1;
            int len = 0;
            while(i >= 0 && s.charAt(i) == ' ') i--;
            while(i >= 0 && s.charAt(i) != ' '){len++;i--;}
            return len;
        }
    }

Log in to reply
 

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