Roman to Integer
LeetCode 13 · ಸುಲಭ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
If cur < next, add next − cur and skip both.
ನಾನು Roman to Integer (LeetCode 13) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Parsing / Conversion ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಸುಲಭ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
Normally symbols add up. The exception is subtractive pairs like IV or CM: a smaller symbol before a larger one means 'larger minus smaller'. Look one symbol ahead to decide.
Approach
- 1
Map each symbol to its value.
- 2
At i, compare cur with the next symbol's value.
- 3
Subtractive pair → add next − cur and jump two; else add cur.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
Look-ahead scanPythonO(n) time · O(1) space
class Solution:
def romanToInt(self, s: str) -> int:
#put in map
#capture next element and current element - IV
#if next element is greater than the current element add next-cur
#else add cur
#do it with a while loop for better control
mpp = {
"I":1,
"V":5,
"X":10,
"L":50,
"C":100,
"D":500,
"M":1000
}
i=0
total=0
while i<len(s):
cur = mpp.get(s[i])
next = mpp.get(s[i+1]) if i+1<len(s) else 0
if cur<next:
total+=next-cur
i+=1
else:
total+=cur
i+=1
return totalRoman to Integer — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
Roman to Integer ಹಿಂದಿನ intuition ಏನು?
Normally symbols add up. The exception is subtractive pairs like IV or CM: a smaller symbol before a larger one means 'larger minus smaller'. Look one symbol ahead to decide.
Roman to Integer (LeetCode 13) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. Map each symbol to its value. 2. At i, compare cur with the next symbol's value. 3. Subtractive pair → add next − cur and jump two; else add cur.
Roman to Integer ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(n). Space: O(1). (Accepted approach: Look-ahead scan.)
Roman to Integer ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?
Guard i + 1 < len(s) when peeking.