美文网首页
LeetCode.python.String.1-5

LeetCode.python.String.1-5

作者: 小异_Summer | 来源:发表于2020-02-22 16:16 被阅读0次

1. 13. Roman to Integer

class Solution:
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        numDict = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
        res = numDict.get(s[-1])
        for i in range(0, len(s)-1):
            if (numDict[s[i]] < numDict[s[i+1]]):
                res -= numDict.get(s[i])
            else:
                res += numDict.get(s[i])
        return res

2. 14. Longest Common Prefix

# 使用Solution2的思路,纵向对比strs每个字符是否相同
class Solution:
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if not strs: #str is empty
            return ""
        
        for i, letter_vertical in enumerate(zip(*strs)): #i_max == the shortest length of strs
            if len(set(letter_vertical)) > 1:
                return strs[0][:i]
        return min(strs)

3. 20. Valid Parentheses

class Solution:
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        stack = []
        opDict = {"]":"[", "}":"{", ")":"("}
        for char in s:
            if char in opDict.values():
                stack.append(char)
            elif char in opDict.keys():
                if stack == [] or opDict[char] != stack.pop(): # pop 移除并返回List最后一个元素
                    return False
            else:
                return False
        return stack == []  # 全部匹配完

4. 28. Implement strStr()

5. 38. Count and Say

相关文章

网友评论

      本文标题:LeetCode.python.String.1-5

      本文链接:https://www.haomeiwen.com/subject/fgyecftx.html