code 4 判断数字是否是回文数
例:Input: 121 Output: tru
Input: -121 Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Input: 10 Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
code:
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x<0:
return 1!=1
n=x
y=0
while n!=0:
y=y*10+n%10
n=n//10
return y==x
笔记:傻的一匹,昨天刚做完一个倒序数字的,这个只需判断倒序后是否和原来相等。思路二:将数字转化为字符串,x.reverse() ,判断是否相等。
code 5
将罗马数字转化为十进制数,特殊点就是4,9,40,90,400,900这些数
例:Input: "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
code:class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
dict={'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
y=0
for i in range(len(s)-1):
if dict[s[i]]<dict[s[i+1]]:
y=y-dict[s[i]]
else:
y=y+dict[s[i]]
return y+dict[s[-1]]
笔记:关键在处理特殊数,利用数字大小判断而不是利用字母的连续,字典运用
code 6: 找出数组中首子母相同的字符串的个数
例: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.
code:class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
result=""
for n in zip(*strs):
if len(set(n)) == 1:
result += n[0]
else:
return result
return result
笔记:zip(*)函数用法
import numpy as np
a=[1,2,3]b=[4,5,6,7]
c=[8,9,10,11,12]
zz=zip(a,b,c)
print(zz)
set() 函数创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。利用set函数确定是否相同。
字符串的初始化:out=""