Tensorum
YouTubeనేర్చుకోవడం ప్రారంభించండి
LeetCode 58 · Other

Length of Last Word

LeetCode 58 · సులభం · పరిష్కారం, intuition & దశలవారీ వాక్‌త్రూ

Skip trailing spaces, count back to a space.

సులభంString
LeetCode లో తెరవండి ↗

నేను Length of Last Word (LeetCode 58) ను ఇలా పరిష్కరించాను — Other ప్యాటర్న్‌లోని ఒక సులభం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.

కింది వివరణ ఇంగ్లీష్‌లో ఉంది.

Intuition

Scan from the end: skip trailing spaces, then count characters until the next space or the start.

Approach

  1. 1

    i at the last index; move left past spaces.

  2. 2

    Count non-space characters moving left.

నేను ఎలా పరిష్కరించాను

Reverse scanPythonO(n) time
class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        #trime white space from right
        i=len(s)-1
        while i>=0 and s[i]==" ":
            i-=1
        length=0
        while i>=0 and s[i]!=" ":
            length+=1
            i-=1
        return length
స్టెప్-త్రూ లోడ్ అవుతోంది…

Length of Last Word — తరచూ అడిగే ప్రశ్నలు

Length of Last Word వెనుక ఉన్న intuition ఏమిటి?

Scan from the end: skip trailing spaces, then count characters until the next space or the start.

Length of Last Word (LeetCode 58) ను ఎలా పరిష్కరించాలి?

1. i at the last index; move left past spaces. 2. Count non-space characters moving left.

Length of Last Word యొక్క time, space complexity ఎంత?

Time: O(n). Space: O(1). (Accepted approach: Reverse scan.)

Length of Last Word లో సాధారణ పొరపాట్లు ఏమిటి?

Trailing spaces are the trap.