Leetcode之Python练习(一)

1.两数之和

# -*- coding:utf-8 -*-
#给定一个整数数列,找出其中和为特定值的那两个数。
#你可以假设每个输入都只会有一种答案,同样的元素不能被重用。
#给定 nums = [2, 7, 11, 15], target = 9
#因为 nums[0] + nums[1] = 2 + 7 = 9
#所以返回 [0, 1]
class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        length=len(nums)
        for i in range(length):
            if target-nums[i] in nums[i+1:]:#在或者不在。成员关系操作符in not in
                return [i,nums.index(target-nums[i],i+1)]#注意索引不包括i本身。限制范围
# arr=[1,2,3,4]
# print(arr.index(4))
s=Solution()

print s.twoSum([3,3],6)

2.两数相加

# -*- coding:utf-8 -*-
#给定两个非空链表来代表两个非负整数,位数按照 *逆序* 方式存储,它们的每个节点只存储 *单个* 数字。将这两数相加会返回一个新的链表。
#你可以假设除了数字 0 之外,这两个数字都不会以零开头。
# Definition for singly-linked list.
class ListNode:
    def __init__(self,x):
        self.val=x
        self.next=None

class Solution:
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        carry=0
        res=n=ListNode(0)
        while l1 or l2 or carry:
            if l1:
                carry+=l1.val
                l1=l1.next
            if l2:
                carry+=l2.val
                l2=l2.next
            carry,val=divmod(carry,10)#返回商,余数
            n.next=n=ListNode(val)
        return res.next

7.颠倒整数

# -*- coding:utf-8 -*-
#
#给定一个范围为 32 位 int 的整数,将其颠倒。

class Solution:
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        if x==0:
            return x
        else:
            x=str(x)
            if '-' in x:
                x=int('-'+"".join(reversed(x[1:])))
            else:
                x=reversed(x)
                x=int("".join(x))
            if abs(x)>2**31:
                return 0
            else:
                return x
    def reverse2(self,x):
        s=str(x)
        if x>=0:
            res=int(s[::-1])
        else:
            res=int("-"+s[1:][::-1])
        return res

9.回文数

# -*- coding:utf-8 -*-
#判断一个整数是否是回文数。不能使用辅助空间。正读反读都一样。负数不是回文数

class Solution:
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        if x<0:
            return False
        else:
            new=int(str(x)[::-1])
            if new==x:
                return True
            else:
                return False
s=Solution()
print s.isPalindrome(121)

13.罗马字转整数

# -*- coding:utf-8 -*-
#给定一个罗马数字,将其转换成整数。
#返回的结果要求在 1 到 3999 的范围内。
#罗马数字采用7个罗马字母作为数字。即I(1)、X(10)、C(100)、M(1000)、V(5)、L(50)、D(500)
#计数方法:
#相同的数连写,所表示的数表示这些数字相加得到的数,III=3
#大数--小数,表示这些数字相加得到的数,VIII=8,XII=12
#小数(I\X\C)--大数,表示大数减小数得到的数。
class Solution:
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        roman={'M':1000,'D':500,'C':100,'L':50,'X':10,'V':5,'I':1}
        sum=0
        for i in range(0,len(s)-1):
            if roman[s[i]]< roman[s[i+1]]:#减去当前的数
                sum-=roman[s[i]]
            else:#包括了如果相邻两个相等,也是相加。加上当前的数
                sum+=roman[s[i]]
        return sum+roman[s[-1]]#别忘了加上最后一个数。

14.最长公共前缀

# -*- coding:utf-8 -*-
#编写一个函数来查找字符串数组中最长的公共前缀字符串。
#先找最短的字符串,然后再遍历这个字符串,与数组中的其他字符串比较,直到不相等,返回
class Solution:
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if not strs:
            return ""
        shortest=min(strs,key=len)#按长度取最小的那个字符串
        for i,ch in enumerate(shortest):
            for other in strs:
                if other[i] !=ch:
                    return shortest[:i]
        return shortest#要注意如果输入的是[""],返回“”

20.有效的括号

# -*- coding:utf-8 -*-
#给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。

#括号必须以正确的顺序关闭,"()" 和 "()[]{}" 是有效的但是 "(]" 和 "([)]" 不是。

class Solution:
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        stack=[]
        dict={"]":"[","}":"{",")":"("}
        for char in s:
            if char in dict.values():
                stack.append(char)
            elif char in dict.keys():

                if stack==[] or dict[char]!=stack[-1]:
                    return False
                else:
                    del stack[-1]#如果想省略此步骤,可以直接用stack.pop()操作,既弹出栈顶,又删除原先的栈。
            else:
                return False
        if len(stack)!=0:
            return False
        return True

s=Solution()
print s.isValid('{}[]')

a=['123','456']
print a.pop()#注意做了pop操作之后原来的list也发生了改变
print a

未完待续。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值