1. Two Sum
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dic = {}
for index, value in enumerate(nums):
sub = target - value
if sub in dic:
return [dic[sub], index]
else:
dic[value] = index
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
revx=int(str(abs(x))[::-1])
if revx>2**31:
return 0
if x<0:
return revx*(-1)
else:
return revx
注意大数
9. Palindrome Number
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x<0:
return False
a=x
b=0
while x>0:
b=b*10+x%10
x//=10
if a==b:
return True
else:
return False
13. Roman to Integer
I
,
V
,
X
,
L
,
C
,
D
and
M
.
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:
I
can be placed beforeV
(5) andX
(10) to make 4 and 9.X
can be placed beforeL
(50) andC
(100) to make 40 and 90.C
can 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.
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
dic={'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
a=0
size=len(s)
i=1
while i<size:
if dic[s[i]]>dic[s[i-1]]:
a=a+dic[s[i]]-dic[s[i-1]]
i+=1
else:
a = a + dic[s[i - 1]]
i+=1
if dic[s[size-1]]<=dic[s[size-2]]:
a=a+dic[s[size-1]]
return a
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 ""
.
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
return ''
size=len(strs)
l=[0 for i in range(size)]
for i in range(size):
l[i]=len(strs[i])
s=sorted(l)[0]
i=0
str=''
flag=1
while i<s:
for j in range(1,len(strs)):
if strs[0][i] != strs[j][i]:
flag=0#应该直接返回,因为不需要执行别的语句
break
if flag==1:
str=str+strs[0][i]
i+=1
return str
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
return ''
str=''
for i in range(len(strs[0])):
for j in range(1,len(strs)):
if i >= len(strs[j]) or strs[j][i] != strs[0][i]:
return str
str=str+strs[0][i]
return str
20. Valid Parentheses
Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
if not s:
return True
def Symmetrical(a,b):
if a=='[' and b==']':
return 1
if a=='{' and b=='}':
return 1
if a=='(' and b==')':
return 1
else:
return 0
size=len(s)
flag=0
if size%2!=0:
return False
else:
for i in range(size//2):
flag=0
if s[i] in ['[','{','(']:
for j in range(1,size):
if Symmetrical(s[i],s[j])==1 and (j-i)%2==1:
flag=1
if flag==0:
return False
else:
for j in range(i):
if Symmetrical(s[j],s[i])==1 and (i-j)%2==1:
flag=1
if flag==0:
return False
return True
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
if not s:
return True
size=len(s)
stack=[' 'for i in range(size)]
top=-1
index=0
while index<size:
if s[index]==')':
if top>=0 and stack[top]=='(':#如果栈里有元素且可以匹配,出栈
top-=1
else:
return False
elif s[index]=='}':
if top>=0 and stack[top]=='{':
top-=1
else:
return False
elif s[index]==']':
if top>=0 and stack[top]=='[':
top-=1
else:
return False
else:#左括号的都进栈,等待被匹配
top+=1
stack[top]=s[index]
index+=1
if top==-1 and index==size:
return True
else:
return False
注意if和elif区别,