【LeetCode算法题库】Day5:Roman to Integer & Longest Common Prefix & 3Sum
【Q13】
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, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
Ican be placed beforeV(5) andX(10) to make 4 and 9.Xcan be placed beforeL(50) andC(100) to make 40 and 90.Ccan be placed beforeD(500) andM(1000) to make 400 and 900.
Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
Example 1:
Input: "III"
Output: 3
Example 2:
Input: "IV"
Output: 4
Example 3:
Input: "IX"
Output: 9
Example 4:
Input: "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
Example 5:
Input: "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. 解法:从高位至低位倒序遍历,遇到遇到I/X/C时判断此时数值,若此时数值大于5/50/500,则对数值依次减去1/10/100,其余情况下加上对应数字即可。
class Solution:
def romanToInt(self, s):
"""
:type s: str
:rtype: int
""" op = 0
for x in reversed(s):
if x=='I':
op += 1 if op<5 else -1
elif x=='V':
op += 5
elif x=='X':
op += 10 if op<50 else -10
elif x=='L':
op += 50
elif x=='C':
op += 100 if op<500 else -100
elif x=='D':
op += 500
else:
op += 1000
return op
【Q14】
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z.
解法:先找到最短的字符串,以此为基准。遍历整个字符串数组,取每个单词依次与该最短字符串比较。
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
""" if len(strs)==0:
return ""
shortestStr = min(strs,key=len) # find shortest string in the list
for i in range(len(shortestStr)):
for s in strs:
if s[i]!=shortestStr[i]:
return shortestStr[:i]
return shortestStr
【Q15】
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4], A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
解法:先固定一个数A,则任务变成寻找数组里的另外两个数,使得这两个数的和Target=0-A,此时问题变成2Sum问题。需要注意的是可能存在数组内有重复元素的问题,此时可通过while语句直接跳过重复元素。
class Solution:
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
""" nums.sort()
N = len(nums)
result = []
for k in range(N):
if k>0 and nums[k]==nums[k-1]:
continue target = 0-nums[k]
i,j = k+1,N-1 while i<j:
if nums[i]+nums[j]==target:
result.append([nums[k],nums[i],nums[j]])
i += 1
j -= 1
while i<j and nums[i]==nums[i-1]:
i += 1
elif nums[i]+nums[j]<target:
i += 1
else:
j -= 1
return result
【LeetCode算法题库】Day5:Roman to Integer & Longest Common Prefix & 3Sum的更多相关文章
- 【LeetCode算法题库】Day4:Regular Expression Matching & Container With Most Water & Integer to Roman
[Q10] Given an input string (s) and a pattern (p), implement regular expression matching with suppor ...
- 【LeetCode算法题库】Day3:Reverse Integer & String to Integer (atoi) & Palindrome Number
[Q7] 把数倒过来 Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Outpu ...
- 【leetcode刷题笔记】Roman to Integer
Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 t ...
- 【LeetCode算法题库】Day7:Remove Nth Node From End of List & Valid Parentheses & Merge Two Lists
[Q19] Given a linked list, remove the n-th node from the end of list and return its head. Example: G ...
- 【LeetCode算法题库】Day2:Median of Two Sorted Arrays & Longest Palindromic Substring & ZigZag Conversion
[Q4] There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of th ...
- 【LeetCode算法题库】Day1:TwoSums & Add Two Numbers & Longest Substring Without Repeating Characters
[Q1] Given an array of integers, return indices of the two numbers such that they add up to a specif ...
- 【算法】LeetCode算法题-Roman To Integer
这是悦乐书的第145次更新,第147篇原创 今天这道题和罗马数字有关,罗马数字也是可以表示整数的,如"I"表示数字1,"IV"表示数字4,下面这道题目就和罗马数 ...
- 【算法】LeetCode算法题-Reverse Integer
这是悦乐书的第143次更新,第145篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第2题(顺位题号是7),给定32位有符号整数,然后将其反转输出.例如: 输入: 123 ...
- LeetCode算法题-Design HashSet(Java实现)
这是悦乐书的第298次更新,第317篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第166题(顺位题号是705).不使用任何内建的hash表库设计一个hash集合,应包含 ...
随机推荐
- SICP 习题 (1.34)解题总结
SICP 习题 1.34的题目比較特别一点.对于没有接触过高阶函数的同学们来说是个非常好的学习机会. 题目是这种,假设我们定义以下的过程: (define (f g) (g 2)) 那么就有: ( ...
- ab网站压力测试命令的参数、输出结果的中文注解
ab命令原理 Apache的ab命令模拟多线程并发请求,测试服务器负载压力,也可以测试nginx.lighthttp.IIS等其它Web服务器的压力. ab命令对发出负载的计算机要求很低,既不会占用很 ...
- Day1 Java编程环境和变量
什么是软件? 软件的基本组成部分是完成其功能的程序. 在日程生活中,可以将程序看成对一系列动作的执行过程的描述. 什么是计算机程序? 为了让计算机执行某些操作或解决某个问题二编写的一系列有序指令的集合 ...
- Js 中的事件委托/事件代理
什么叫事件委托/事件代理呢 ? JavaScript高级程序设计上讲:事件委托就是利用事件冒泡,只指定一个事件处理程序,就可以管理某一类型的所有事件. 事件冒泡: 当事件发生后,这个事件就要开始传 ...
- virtualbox+vagrant学习-2(command cli)-4-vagrant global-status命令
Global Status 格式: vagrant global-status 这个命令将告诉你当前登录的用户系统上所有活跃的vagrant环境的状态. userdeMacBook-Pro:~ use ...
- springboot不使用内置tomcat启动,用jetty或undertow
Spring Boot启动程序通常使用Tomcat作为默认的嵌入式服务器.如果需要更改 - 您可以排除Tomcat依赖项并改为包含Jetty或Undertow: jetty配置: <depend ...
- web常用的正则表达式
1. 平时做网站经常要用正则表达式,下面是一些讲解和例子,仅供大家参考和修改使用: 2. "^\d+$" //非负整数(正整数 + 0) 3. "^[0 ...
- launch edge 和 latch edge 延迟
本文转自 http://www.cnblogs.com/inet2012/archive/2012/03/07/2384149.html launch edge和latch edge分别是指一条路径的 ...
- [NOIp2016]蚯蚓 (队列)
#\(\color{red}{\mathcal{Description}}\) LInk 这道题是个\(zz\)题 #\(\color{red}{\mathcal{Solution}}\) 我们考虑如 ...
- P1441 砝码称重
题目描述 现有n个砝码,重量分别为a1,a2,a3,……,an,在去掉m个砝码后,问最多能称量出多少不同的重量(不包括0). 输入输出格式 输入格式: 输入文件weight.in的第1行为有两个整数n ...