数据结构与算法 学习笔记(5):字符串

数据结构与算法 学习笔记(5)- 字符串

本次笔记记录了LeetCode中关于字符串的一些问题,并给出了相应的思路说明和代码。题目编号与LeetCode对应,方便查找。

题目1:LeetCode 13. Roman to Integer

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, The number twenty seven is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.

Example :
Input: “MCMXCIV”
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

"""
思路:
1.构建将罗马数字映射为阿拉伯数字的字典
2.依次读取字符串中的字符,并判断当前字符的值是否小于后一字符的值;
3.若符合,说明有“抽象”,因为循环到下一位时会求和,所以当前应该求差(即把两个字符抽象成一个);
4.若不符,则把当前的数和之前的和相加就行;
5.当然,如果当前的i是字符串的末尾,i+1肯定不存在,直接把当前值加入到z中求和。
"""
class Solution(object):
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        roman = {
   'M': 1000,'D': 500 ,'C': 100,'L': 50,'X': 10,'V': 5,'I': 1}
        z = 0
        k = len(s)
        for i in range(0, k):
            if i == k-1:
                z += roman[s[i]]
            else:
                if roman[s[i]] < roman[s[i+1]]:
                    z -= roman[s[i]]
                else:
                    z += roman[s[i]]
        return z
题目2:LeetCode 14. Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.If there is no common prefix, return an empty string “”.

Example 1:
Input: [“flower”,“flow”,“flight”]
Output: “fl”
Example 2:
input: [“dog”,“racecar”,“car”]
Output: “”

"""
思路:
1.目标是找共同的最长前缀。
2.如果找出最小的串和最大的串,那么它们的共同前缀就是表里所有串的共同前缀(反证可得)
3.然后对比最小串和最大串前缀,如果第i位不一样,返回前i-1位
4.如果遍历完了最小串,还是相同,则最小串本身就是共同前缀
"""
class Solution(object):
    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """
        if not strs:
            return ""
        min_s = min(strs)
        max_s = max(strs)
        for i in range(0,len(min_s)):
            if max_s[i] != min_s[i]:
                return min_s[:i] #切片,是不包括i的,到i-1为止
        return min_s
题目3:LeetCode 20. Valid Parentheses

Given a string containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.

An input string is valid if:

  • Open brackets must be closed by the same type of brackets.
  • Open brackets must be closed in the correct order.
  • Note that an empty string is also considered valid.

Example :

Input: “()[]{}” _______Output: true
Input: “([)]” ________Output: false
Input: “{ }”________Output: true

"""
思路:用栈入栈出来做括号的匹配
1.先把括号用字典进行配对,方便比较操作
2.读取s中的字符,如果不是任何一个左右括号,返回False
3.如果是左括号,存入栈中;
4.如果是右括号,判断栈中是否有左括号
    1rd若没有,说明S中的右括号出现在左括号之前,返回False;
    2rd若有,是否能和最后一个进入栈中的左括号匹配,不成功则返回False,成功则读取s的下一个字符
5.读取完所有的字符后,若stack中没有任何字符,说明匹配了;反之则未匹配
"""
class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        stack = []
        dict = {
   "]":"[", "}":"{", ")":"("}
        for char in s:
            if char in dict.values():
                stack.append(char)
            elif char in dict.keys():
                if  stack == []:
                    return False
                elif dict[char] != stack.pop():
                    return False
            else: #s中有不在字典中的字符
                return False
        if stack == []:
            return True
        else:
            return False
题目4:LeetCode 28. Implement strStr()

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example :
Input: haystack = “hello”, needle = “ll”
Output: 2
Input: haystack = “aaaaa”, needle = “bba”
Output: -1

"""
若haystack长度为n,needle长度为m
方法一:利用循环 比较
    这种方法的时间复杂度:O(m*n)
方法二:利用python切片
    这种方法的时间复杂度:O((m-n )* n)
方法三:利用KMP算法
    这种方法的时间复杂度:O(m+n)
"""
class Solution(object):
    def strStr(self, haystack
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值