Longest Common Prefix
LeetCode 14 · ಸುಲಭ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
Shrink a candidate prefix until every word starts with it.
ನಾನು Longest Common Prefix (LeetCode 14) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Prefix / Misc ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಸುಲಭ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
Start with the first word as the candidate prefix. For each other word, chop characters off the end of the candidate until the word starts with it. Whatever survives every word is the answer.
Approach
- 1
prefix = strs[0].
- 2
For each word, while it doesn't start with prefix, drop the last character.
- 3
Empty prefix → return ''.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
Shrinking prefixPythonO(S) time
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
i=1
prefix = strs[0]
while i<len(strs):
cur_word = strs[i]
while not cur_word.startswith(prefix):
prefix=prefix[:len(prefix)-1]
if not prefix:
return ""
i+=1
return prefixLongest Common Prefix — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
Longest Common Prefix ಹಿಂದಿನ intuition ಏನು?
Start with the first word as the candidate prefix. For each other word, chop characters off the end of the candidate until the word starts with it. Whatever survives every word is the answer.
Longest Common Prefix (LeetCode 14) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. prefix = strs[0]. 2. For each word, while it doesn't start with prefix, drop the last character. 3. Empty prefix → return ''.
Longest Common Prefix ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(S) — total characters. Space: O(1). (Accepted approach: Shrinking prefix.)
Longest Common Prefix ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?
Return early when the prefix becomes empty.