14. Longest Common Prefix
题目简介:给定一个包含若干字符串的列表,求其最长的公共前缀。
解题思路:若列表非空,先对列表排序,之后只需对排序后的列表首尾的字符串求最长公共前缀即可。若列表为空,返回空串。代码如下:
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
res = ""
lstrs = len(strs)
if strs is not None and lstrs > 0:
strs.sort()
l1 = len(strs[0])
l2 = len(strs[lstrs-1])
l = min(l1,l2)
for i in xrange(l):
if strs[0][i] == strs[lstrs-1][i]:
res+=strs[0][i]
else:
return res
return res
20. Valid Parentheses
题目简介:给定一串由大中小括号组成的字符串,判断该字符串是否符合括号匹配规则。
解题思路:经典的用栈来解决的题目。代码如下:
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
l = len(s)
if l > 0 and l % 2 == 0:
stack = []
lstack = 0
left = '([{'
right = ')]}'
for c in s:
if c in left:
stack.append(c)
lstack+=1
else:
if lstack <= 0:
return False
if (c == right[0] and stack[lstack-1] == left[0]) or (c == right[1] and stack[lstack-1] == left[1]) or (c == right[2] and stack[lstack-1] == left[2]):
stack.pop()
lstack-=1
if not lstack:
return True
return False
return False
67. Add Binary
题目简介:求两个二进制数(字符串)相加之和,返回二进制结果
解题思路:利用int()和bin()内置函数可以十分方便的实现十进制和二进制之间的转换。代码如下:
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
aint,bint = int(a,2),int(b,2)
return bin(aint+bint)[2:]
125. Valid Palindrome
题目简介:给定一串字符串,判断其中的数字字母是否回文。
解题思路:利用re模块对原串进行分割,去除数字字母之外的字符,并将字母全转为小写,再判断新串左右两边是否对称即可。代码如下:
import re
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
s2 = ''.join(re.split('[^0-9a-zA-Z]',s)).lower()
l = len(s2)
if l < 2:
return True
step = l//2
return s2[:step] == s2[-step:][::-1]
387. First Unique Character in a String
题目简介:找到一串字符中第一个无重复元素的元素的下标,若不存在这样的元素,返回-1。
解题思路:利用字母表进行遍历,对每一个字符进行判断是否是唯一的。代码如下:
class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
index = len(s)
alphabet = "abcdefghijklmnopqrstuvwxyz"
for i in alphabet:
x = s.find(i)
if x != -1:
y = s.rfind(i)
if x == y:
if x < index:
index = x
if index != len(s):
return index
return -1
459. Repeated Substring Pattern
题目简介:判断一个字符串是否是由若干(大于2)相同子串拼接而成的。
解题思路:需要用到一点数学证明。可知如果一个字符串s是由若干相同子串拼接而成的,那么他本身必定是ss(自身的拼接)去掉头尾字符之后的子串。代码如下:
class Solution(object):
def repeatedSubstringPattern(self, s):
"""
:type s: str
:rtype: bool
"""
s2 = s*2
return s in s2[1:-1]
606. Construct String from Binary Tree
题目简介:如题。
解题思路:递归。代码如下
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def tree2str(self, t):
"""
:type t: TreeNode
:rtype: str
"""
if t == None:
return ""
elif t.left == None and t.right == None:
return str(t.val)
elif t.left == None:
return str(t.val)+"()"+"("+self.tree2str(t.right)+")"
elif t.right == None:
return str(t.val)+"("+self.tree2str(t.left)+")"
else:
return str(t.val)+"("+self.tree2str(t.left)+")"+"("+self.tree2str(t.right)+")"