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           
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容