leetcode每周记录

(暂时只贴上代码和简单说明

1、Remove Element

code:

class Solution(object):
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        count = nums.count(val)
        for i in xrange(count):
            nums.remove(val)
        return len(nums)

2、Combination Sum

 code:

class Solution(object):
    def combinationSum(self, candidates, target):
        res = []
        candidates.sort()
        self.dfs(candidates, target, 0, [], res)
        return res
    
    def dfs(self, nums, target, index, path, res):
        if target < 0:
            return  # backtracking
        if target == 0:
            res.append(path)
            return 
        for i in xrange(index, len(nums)):
            self.dfs(nums, target-nums[i], i, path+[nums[i]], res)

3、Substring with Concatenation of All Words

 该题目暂时没有写出accepted的方法,试了两种方法都超时了:

class Solution(object):
    def findSubstring(self, s, words):
        """
        :type s: str
        :type words: List[str]
        :rtype: List[int]
        """
        ret = []
        indices = []
        self.findAllCombination('', words, ret)
        for _ret in set(ret):
            index = []
            _currLength = 0
            _s = s
            while(1):
                try:
                    _index = _s.index(_ret)
                    index.append(_index + _currLength)
                    _currLength = _index + len(_ret)
                    _s = _s[_currLength:]
                except:
                    break
            indices += index
        return indices

    
    def findAllCombination(self, currWord, leftWords, ret):
        if not leftWords:
            ret.append(currWord)
            return
        for word in leftWords:
            _leftWords = [x for x in leftWords]
            _leftWords.remove(word)
            self.findAllCombination(currWord+word, _leftWords, ret)
class Solution(object):
    def findSubstring(self, s, words):
        """
        :type s: str
        :type words: List[str]
        :rtype: List[int]
        """
        if not words:
            return []
        indices = []
        length = len(words[0])
        findedWords = []
        for word in words:
            if word in findedWords:
                continue
            _currIndex = 0
            _s = s
            while(1):
                try:
                    index = _s.index(word)
                except:
                    break
                _leftWords = [x for x in words]
                _leftWords.remove(word)
                valid, newLoc = self.checkIfValid(index, length, _s,_leftWords)
                if valid:
                    indices.append(index + _currIndex)
                    _currIndex += (index)
                else:
                    _currIndex += (newLoc)
                _s = s[_currIndex:]
            findedWords.append(word)
        return indices

    
    def checkIfValid(self, index, length, s, leftWords):
        _s = s
        while(leftWords):
            word = _s[index+length:index+2*length]
            if word in leftWords:
                leftWords.remove(word)
                index += length
            else:
                return False, index
        return True, index

4、Longest Palindromic Substring

 beat仅5%,待优化

class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        if not s:
            return ''
        if self.checkIfPalindrome(s):
            return s
        length = len(s)
        cut = 1
        ret = ''
        while(cut < length):
            l = cut
            r = 0
            flag = False
            while(r <= cut):
                if self.checkIfPalindrome(s[l:-r if r != 0 else None]):
                    flag = True
                    break
                l -= 1
                r += 1
            if flag:
                ret = s[l:-r if r != 0 else None]
                break
            else:
                cut += 1
        return ret
        
        
    def checkIfPalindrome(self, s):
        length = len(s)
        halfLength = length / 2
        if length % 2 == 1:
            right = s[halfLength + 1:]
            return s[0:halfLength] == right[::-1]
        else:
            right = s[halfLength:]
            return s[0:halfLength] == right[::-1]

5、ZigZag Conversion

beat仅6%,待优化

class Solution(object):
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        if not s:
            return ''
        if numRows == 1:
            return s
        totalWordNum = len(s)
        partWordNum = numRows + (numRows - 2)
        partNum = (totalWordNum / partWordNum) + 1
        partLength = numRows - 1
        strs = [[''] * (partLength * partNum) for i in xrange(numRows)]
        currRow = 0
        currWordNum = 0
        currDepth = 0
        for index, word in enumerate(s):
            try:
                if currWordNum < numRows:
                    strs[currRow][currDepth] = word
                    currWordNum += 1
                    if currWordNum < numRows:
                        currRow += 1
                elif numRows <= currWordNum < partWordNum:
                    currRow -= 1
                    currDepth += 1
                    currWordNum += 1
                    strs[currRow][currDepth] = word
                else:
                    currDepth += 1
                    currWordNum = 1
                    strs[0][currDepth] = word
                    currRow = 1
            except:
                print index, word, currDepth
        newStr = ''
        for wordList in strs:
            _str = ''
            for word in wordList:
                _str += word
            newStr += _str
        return newStr
原文地址:https://www.cnblogs.com/HorribleMe/p/12502432.html