Length of Last Word
LeetCode 58 · సులభం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
Skip trailing spaces, count back to a space.
నేను 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
i at the last index; move left past spaces.
- 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 lengthLength 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.