python leetcode简单练习(1)
9.回文数
方法思路
处理特殊情况:
负数不可能是回文数。
末尾为0的非零整数不可能是回文数。
反转一半数字:
通过逐位反转整数的后半部分,直到反转的部分不小于剩余的前半部分。
比较反转后的部分与剩余部分是否相等(偶数位情况)或反转部分除以10后是否与剩余部分相等(奇数位情况)。
注意对特殊值0的处理
class Solution(object):
def isPalindrome(self,x):
if x < 0 or (x%10 == 0 and x != 0) :
return False
else:
a = 0
while x > a:
a = a * 10 + x % 10
x = x // 10
if x == a or a//10 == x :
return True
else:
return False
13.罗马数字转整数
#13.罗马数字转整数
class solution(object):
def romanToInt(self,s):
roman_to_int = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
}
total = 0
n = len(s)
for i in range(n-1):
current_s = roman_to_int[s[i]]
next_s = roman_to_int[s[i+1]]
if current_s < next_s:
total -= roman_to_int[s[i]]
else:
total += roman_to_int[s[i]]
total += roman_to_int[s[-1]]
return total
14.最长公共前缀
方法思路
处理特殊情况:如果输入数组为空,直接返回空字符串。
基准字符串:以第一个字符串作为基准,逐个字符进行比较。
逐字符检查:遍历基准字符串的每个字符位置,检查其他字符串在该位置上的字符是否相同。
终止条件:若遇到任一字符串长度不足或字符不匹配,立即返回当前已匹配的前缀部分。
返回结果:若所有字符均匹配,返回整个基准字符串作为最长公共前缀。
class Solution(object):
def longestCommonPrefix(self,strs):
if not strs:
return ""
else:
first_s = strs[0]
for i in range(len(first_s)):
current_s = first_s[i]
for j in strs[1:]:
if i >= len(j) or j[i] != current_s:
return first_s[:i]
return first_s