leetcode记录

3. Longest Substring Without Repeating Characters

3.1 改善代码

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        subdict ={}
        start = end = 0
        maxlen = 0
        while end < len(s):
            if s[end] in subdict:
                newStart = subdict[s[end]]
                for i in range(start, newStart):
                    subdict.pop(s[i])
                start = newStart + 1
                #重复值在substr的value要变成当前的end位置
                subdict[s[newStart]] = end

            else:
                subdict[s[end]]=end
                if end - start + 1 > maxlen:
                    maxlen = end - start +1
            end += 1
        return maxlen

13. Roman to Integer

13.1 初始代码

class Solution:
    def romanToInt(self, s: str) -> int:
        values = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
        res = 0
        pos = 0
        while pos <= len(s)-1:
            if pos + 1 <= len(s) - 1 and s[pos:pos+2] in ('IV', 'IX', 'XL', 'XC', 'CD', 'CM'):
                  res = res - values[s[pos]] + values[s[pos+1]]
                  pos += 2
            else:
                  res = res + values[s[pos]]
                  pos += 1
        return res           
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容