@chanvee 2014-12-09T11:34:16.000000Z 字数 3891 阅读 20736

# LeetCode 题解一（python版）

LeetCode, Python

## Reverse Words in a String

class Solution:    # @param s, a string    # @return a string    def reverseWords(self, s):        tmp = s.split(' ') # 将字符串分割为列表        while '' in tmp:   # 清除空元素            tmp.remove('')        tmp.reverse()      # 列表倒序        tmp = ' '.join(tmp) #列表转化为字符串，并以空格连接        return(tmp)

## Single Number

class Solution:    # @param A, a list of integer    # @return an integer    def singleNumber(self, A):        result = 0        for i in A:        # 相同元素异或为0,0与任何数异或等于任何数，有a^b^a = b        # 此外，异或还可以用于两个元素交换a=a^b^(b=a)            result = result^i           return(result)

## Single Number II

class Solution:    # @param A, a list of integer    # @return an integer    def singleNumber(self, A):        ones, twos = 0, 0        for ele in A:             ones = ones^ele & ~twos             twos = twos^ele & ~ones        return(ones)

def singleNumber(A,m,n):        tmp = [0]*(m-1)        for ele in A:             for i in range(m-1):                tmp[i] = tmp[i]^ele                for j in range(m-1):                    if i != j:                        tmp[i] = tmp[i] & ~tmp[j]        return(tmp[n-1])

## Valid Palindrome

import re # 正则表达式包含在re里面class Solution:    # @param s, a string    # @return a boolean    def isPalindrome(self, s):        s = s.lower() # 首先将字符串转为小写        s = re.sub('[^A-Za-z0-9]','',s) # 正则表达式去除非字母和数字的符号        if s == s[::-1]: # 如果是回文，即正序和逆序一样            return(True)        else:            return(False)

## Merge Sorted Array

class Solution:    # @param A  a list of integers    # @param m  an integer, length of A    # @param B  a list of integers    # @param n  an integer, length of B    # @return nothing    def merge(self, A, m, B, n):        for i in range(m+n-1, -1, -1):             if m == 0 or (n > 0 and B[n-1] > A[m-1]): # 判断A、B是否为空                A[i] = B[n-1]                n -= 1            else:                A[i] = A[m-1]                m -= 1        return(A)

## Climbing Stairs

class Solution:    # @param n, an integer    # @return an integer    def climbStairs(self, n):        f = [1, 2]        for i in range(2,n):              f.append(f[i-2] + f[i-1])        return(f[n-1])

## Plus One

class Solution:    # @param digits, a list of integer digits    # @return a list of integer digits    def plusOne(self, digits):        flag = 1        for i in range(len(digits)-1, -1, -1):            digits[i] = (digits[i] + 1) % 10 # 加1模10，如果没有进位则跳出循环，否则高一位加1            if digits[i]:                flag = 0                break         if flag: # 如果每一位都进位了，则在数组第一位添加1            digits.insert(0,1)        return(digits)

## Remove Element

class Solution:    # @param    A       a list of integers    # @param    elem    an integer, value need to be removed    # @return an integer    def removeElement(self, A, elem):        while elem in A:            A.remove(elem)        return(len(A))

## Reverse Integer

class Solution:    # @return an integer    def reverse(self, x):        if x >=0:        x = '%d' %x  # Convert to string        if int(x[::-1]) > (2 ** 31-1):            return 0;        else:            return(int(x[::-1])) # reverse    else:        x = abs(x)        x = '%d' %x           if int("-" + x[::-1]) < -2 ** 31:            return 0        else:            return(int("-" + x[::-1]))

## Two Sum

class Solution:    # @return a tuple, (index1, index2)    def twoSum(self, num, target):        tmp = {}        for i in range(len(num)):            if target - num[i] in tmp:                return(tmp[target - num[i]] +1, i + 1)            else:                tmp[num[i]] = i;

• 私有
• 公开
• 删除