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.