Tensorum
YouTubeसीखना शुरू करें
LeetCode 58 · Other

Length of Last Word

LeetCode 58 · आसान · समाधान, intuition और कदम-दर-कदम वॉकथ्रू

Skip trailing spaces, count back to a space.

आसानString

मैंने 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.