I tried LeetCode every day 13. Roman to Integer (Python, Go)

Introduction

@Ishishow is running a free English word site E-tan.

I would like to work on letcode every day to improve my ability as a programmer and give my own way of solving it.

What is Leetcode

leetcode.com This is the practice of coding interviews for software developers. A total of more than 1,500 coding questions have been posted, and it seems that the same questions are often asked in actual interviews.

Introduction to Go language + algorithm I will solve it with Golang and Python to strengthen my brain. (Python is weak but experienced)

4th question (problem 13)

  1. Roman to Integer

--Problem content (Japanese translation)

: Roman numerals are represented by seven different symbols I, V, X, L, C, D and M. Symbol value I 1 V 5 X 10 L 50 C 100 D 500 M 1000

For example, Roman numerals`2`Yo`II`Written in, only the two are added together.`12`Is written`XII`is`X + II`.. This is simple. number`27`Is written`XXVII`is`XX + V + II`。

Roman numerals are usually written from left to right, from maximum to minimum. However, the number 4 is not`IIII`.. Instead, the fourth number is`IV`.. Is written. One is before 5, so subtract it to 4. The same principle is written`IX`It also applies to number 9. There are six examples where subtraction is used:

- `I``V`(5) and`X`It can be placed in front of (10) to make 4 and 9.
- `X``L`(50) and`C`It can be placed in front of (100) to make 40 and 90.
- `C``D`(500) and`M`You can place it before (1000) to create 400 and 900.

Given a Roman numeral, convert it to an integer.

Example 1:

Input: s = "III"
Output: 3

Example 2:

Input: s = "IV"
Output: 4

Example 3:

Input: s = "IX"
Output: 9

Example 4:

Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.

Example 5:

Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

Tips

I - 1
V - 5
X - 10
L - 50
C - 100
D - 500
M - 1000

**Rules:**
\* If I comes before V or X, subtract 1 eg: IV = 4 and IX = 9
\* If X comes before L or C, subtract 10 eg: XL = 40 and XC = 90
\* If C comes before D or M, subtract 100 eg: CD = 400 and CM = 900 

Way of thinking

  1. Make a hash map with reference to the hint
  2. Read the character string character by character, compare the number corresponding to the character with the number corresponding to the subsequent character, add it as it is if it is large, and add the value obtained by subtracting that character if it is small (code It may be faster to see)

Explanation

  1. Go sets the initial value with the map function. (I used make for the problem of 1.Two Sum, but this time the initial value is included, so map is fine)

  2. Python is easy to manipulate strings, so I'll look at it later, but in Go, I'll convert it to an array and look at the previous character.

--Answer code

class Solution(object):
    def romanToInt(self, s):
        roman = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
        res, i = 0, 0
        for i in range(len(s)):
            curr, nxt = s[i], s[i+1:i+2]
            if nxt and roman[curr] < roman[nxt]:
                res -= roman[curr]
            else:
                res += roman[curr]
        return res

String manipulation is easier with slices

--I'll write it in Go too!

import "strings"

func romanToInt(s string) int {
    var number int = 0
    var carry int = 0
    hashT := map[string]int{
            "I": 1,
            "V": 5,
            "X": 10,
            "L": 50,
            "C": 100,
            "D": 500,
            "M": 1000,
    }

    for _, v := range strings.Split(s, "") {
            if carry < hashT[v] {
                    number = number - (carry * 2) + hashT[v]
            } else {
                    number = number + hashT[v]
            }
            carry = hashT[v]
    }
    return number
}

I'm looking at the previous number with a variable called carry. Since the previous number is added once, when the latter number is larger, the number is subtracted twice.

I also imported the strings package because I used split to make the strings an array.

Go and Python execution time

From the left, RunTime, Memory, language.

キャプチャ.PNG

Recommended Posts

I tried LeetCode every day 13. Roman to Integer (Python, Go)
I tried LeetCode every day 112. Path Sum (Python, Go)
I tried LeetCode every day 20. Valid Parentheses (Python, Go)
I tried LeetCode every day 136. Single Number (Python, Go)
I tried LeetCode every day 118. Pascal's Triangle (Python, Go)
I tried LeetCode every day 125. Valid Palindrome (Python, Go)
I tried LeetCode every day 155. Min Stack (Python, Go)
I tried LeetCode every day 9. Palindrome Number (Python, Go)
I tried LeetCode every day 1. Two Sum (Python, Go)
I tried LeetCode every day 141. Linked List Cycle (Python, Go)
I tried LeetCode every day 110. Balanced Binary Tree (Python, Go)
I tried LeetCode every day 14.Longest Common Prefix (Python, Go)
I tried LeetCode every day 119. Pascal's Triangle II (Python, Go)
I tried LeetCode every day 121 Best Time to Buy and Sell Stock (Python, Go)
I tried LeetCode every day 108. Convert Sorted Array to Binary Search Tree (Python, Go)
I tried LeetCode every day 21. Merge Two Sorted Lists (Python, Go)
I tried LeetCode every day 168. Excel Sheet Column Title (Python, Go)
I tried LeetCode every day 122. Best Time to Buy and Sell Stock II (Python, Go)
I tried LeetCode every day 111. Minimum Depth of Binary Tree (Python, Go)
I tried LeetCode every day 26. Remove Duplicates from Sorted Array (Python, Go)
I tried LeetCode every day 160. Intersection of Two Linked Lists (Python, Go)
I tried LeetCode every day 167. Two Sum II --Input array is sorted (Python, Go)
I tried to touch Python (installation)
I tried Grumpy (Go running Python).
I tried to summarize Python exception handling
I tried to implement PLSA in Python
I tried to implement permutation in Python
I tried to implement PLSA in Python 2
Python3 standard input I tried to summarize
I tried to implement ADALINE in Python
I tried to implement PPO in Python
[Python] I tried to calculate TF-IDF steadily
I tried to touch Python (basic syntax)
I tried to get CloudWatch data with Python
I tried to output LLVM IR with Python
I tried to implement TOPIC MODEL in Python
I tried running faiss with python, Go, Rust
I tried to automate sushi making with python
I tried to implement selection sort in python
LeetCode I tried to summarize the simple ones
[LIVE] I tried to deliver the sunrise and sunset times nationwide every day
I tried Python> autopep8
I tried to debug.
I tried to paste
I tried Python> decorator
I tried to graph the packages installed in Python
I tried to summarize how to use matplotlib of python
I tried to implement Minesweeper on terminal with python
I tried to get started with blender python script_Part 01
I tried to touch the CSV file with Python
I tried to draw a route map with Python
Let Code Day74 starting from zero "12. Integer to Roman"
I tried to solve the soma cube with python
I tried to implement a pseudo pachislot in Python
Continuation ・ I tried to make Slackbot after studying Python3
I tried to get started with blender python script_Part 02
I tried to implement Dragon Quest poker in Python
I tried to implement an artificial perceptron with python
I tried to implement GA (genetic algorithm) in Python
[Go + Gin] I tried to build a Docker environment
[Python] I tried to graph the top 10 eyeshadow rankings