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.