DEV Community

Debesh P.
Debesh P.

Posted on

58. Length of Last Word | LeetCode | Top Interview 150 | Coding Questions

Problem Link

https://leetcode.com/problems/length-of-last-word/


Detailed Step-by-Step Explanation

https://leetcode.com/problems/length-of-last-word/solutions/7439461/best-solution-in-the-world-most-optimal-wkarc


leetcode 58


Solution

class Solution {
    public int lengthOfLastWord(String s) {

        int n = s.length();
        int count = 0;

        for(int i=n-1; i>=0; i--) {
            if(s.charAt(i) != ' ') {
                count++;
            }

            else {
                if(count > 0) {
                    return count;
                }
            }
        }

        return count;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)