Word Pattern
LeetCode 290 · ಸುಲಭ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
Last-seen index per letter and per word must agree.
ನಾನು Word Pattern (LeetCode 290) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Hashing / Frequency ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಸುಲಭ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
Same idea as isomorphic strings, but between pattern letters and words: each letter and its word must have been last seen at the same index.
Approach
- 1
Split s into words; lengths must match.
- 2
Compare stored indices for pattern[i] and words[i].
- 3
Record the current index for both.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
Last-seen indicesPythonO(n) time · O(n) space
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
pattern_mpp = {}
s_mpp = {}
words = s.split(" ")
if len(pattern)!=len(words):
return False
for i in range(len(pattern)):
char = pattern[i]
word = words[i]
if pattern_mpp.get(char,-1)!=s_mpp.get(word,-1):
return False
pattern_mpp[char]=i
s_mpp[word]=i
return TrueWord Pattern — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
Word Pattern ಹಿಂದಿನ intuition ಏನು?
Same idea as isomorphic strings, but between pattern letters and words: each letter and its word must have been last seen at the same index.
Word Pattern (LeetCode 290) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. Split s into words; lengths must match. 2. Compare stored indices for pattern[i] and words[i]. 3. Record the current index for both.
Word Pattern ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(n). Space: O(n). (Accepted approach: Last-seen indices.)
Word Pattern ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?
Length mismatch is an immediate False.