码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 其他题

时间:2020-05-10 19:02:55      阅读:55      评论:0      收藏:0      [点我收藏+]

标签:for   max   cte   Fix   mic   repeat   substr   https   ems   

leetcode 3.无重复字符的最长子串

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        if not s: return 0
        s_dict, start, cur_len, max_len = {}, 0, 0, 0
        for i in range(len(s)):
            if s[i] in s_dict and start<=s_dict[s[i]]:
                start = s_dict[s[i]] + 1
            s_dict[s[i]] = i
            cur_len = i-start+1
            max_len = max(max_len, cur_len)
        return max_len

leetcode 5.最长回文子串

class Solution(object):
    def longestPalindrome(self, s):
        def helper(i, j):
            while i>=0 and j<n and s[i]==s[j]:
                i-=1; j+=1
                if len(self.res)<j-i-1:
                    self.res = s[i+1:j]
        if not s: return s
        n = len(s)
        self.res = ‘‘
        for i in range(n):
            helper(i, i)
            helper(i, i+1)
        return self.res
# 求解
s = Solution()
s.longestPalindrome(‘babad‘)
# return
‘bab‘

leetcode 6.Z字形变换

class Solution(object):
    def convert(self, s, numRows):
        if numRows<2: return s
        res = [‘‘ for _ in range(numRows)]
        start = 0 
        flag = -1
        for c in s:
            res[start] += c
            if start==0 or start==numRows-1: flag = -flag
            start += flag
        return ‘‘.join(res)
# 求解
s = Solution()
s.convert(‘LEETCODEISHIRING‘, 3)

leetcode 7.整数反转

class Solution(object):
    def reverse(self, x):
        res = 0
        flag = 1 if x>0 else -1
        x = str(abs(x))
        for i in range(len(x)):
            res += int(x[i])*pow(10,i)
        return res*flag if -2**31<=res<=2**31-1 else 0

leetcode 8.字符串转换整数 (atoi)

class Solution(object):
    def myAtoi(self, str):
        import re
        s = re.findall(r‘^[\+\-]?\d+‘, str.strip())
        if not s: 
            return 0
        elif int(s[0])<=-2**31:
            return -2**31
        elif int(s[0])>=2**31-1:
            return 2**31-1
        else:
            return int(s[0])

leetcode 14.最长公共前缀

class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if not strs: return ‘‘
        s1 = min(strs)
        s2 = max(strs)
        for index, value in enumerate(s1):
            if value!=s2[index]:
                return s1[:index]
        return s1

leetcode 其他题

标签:for   max   cte   Fix   mic   repeat   substr   https   ems   

原文地址:https://www.cnblogs.com/yutingting/p/12737054.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!