My Java solution without using library function except length() and charAt()


  • 0
    J
    public class Solution {
        public int lengthOfLastWord(String s) {
            if(s == null || s.length() == 0)
                return 0;
            int count = 0;
            int index = s.length() - 1;
            while(index >=0 && s.charAt(index) == ' ')
                index--;
            while(index >= 0 && s.charAt(index) != ' '){
                count++;
                index--;
            }
            return count;
        }
    }

  • 0
    0

    My JAVA solution using trim and charAt

    public int lengthOfLastWord(String s) {
                int length = 0;
                if (s != null) {
                    s = s.trim();
                    for(int i=s.length()-1;i>= 0;i--){
                        if(s.charAt(i)==' ')
                            break;
                        length++;
                    }
                }
                return length;
            }

Log in to reply
 

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