Java code without using method in library


  • 0

    Using trim() will be more elegant for sure. But as it's an interview question, maybe we should avoid using any kind of methods in library.

    Here is my solution:

    public int lengthOfLastWord(String s) {
            if (s == null || s.length() == 0) {
                return 0;
            }
            int c = 0;
            int i = s.length() - 1;
            while (i >= 0) {
                if (s.charAt(i) == ' ' && c == 0) { // trim
                    i--;
                } else if (s.charAt(i) != ' ') {
                    i--;
                    c++;
                } else {
                    break;
                }
            }
            return c;
        }
    

Log in to reply
 

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