Share my primitive solution (Java/C++/Python)


  • 0
    F

    Forward (slower) 8ms

    Java:

        public int lengthOfLastWord(String s) {
            int counter = 0;
            int last = 0;
            for (int i=0; i < s.length(); i++){
                char c = s.charAt(i);
                if (c == ' '){
                    if (counter != 0){
                        last = counter;
                        counter = 0;
                    }
                }
                else counter ++;
            }
            return counter != 0 ? counter : last;
        }
    

    Backward (faster)

    Java: (5ms)

        public int lengthOfLastWord(String s) {
            int counter = 0;
            for (int i = s.length() -1; i>= 0; i--){
                char c = s.charAt(i);
                if (c == ' '){
                    if (counter != 0) return counter;
                }
                else counter ++;
            }
            return counter;
        }
    

    C++: (3ms)

    class Solution {
    public:
        int lengthOfLastWord(string s) {
            int counter = 0;
            for (int i = s.length() -1; i>= 0; i--){
                if (s[i] == ' '){
                    if (counter != 0) return counter;
                }
                else counter ++;
            }
            return counter;
        }
    };
    

    Python: (36ms)

        def lengthOfLastWord(self, s):
            """
            :type s: str
            :rtype: int
            """
            counter = 0
            for i in range(len(s)-1,-1,-1):
                if s[i] == ' ':
                    if counter != 0:
                        return counter
                else:
                    counter +=1
            return counter
    

Log in to reply
 

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