leetcode刷题之字符串处理

本文深入探讨了寻找字符串中最长无重复字符子串及最长回文子串的算法实现,提供了多种解决思路,包括暴力排序、队列思想、哈希表应用等,对比不同方法的时间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

3. Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: “abcabcbb”
Output: 3
Explanation: The answer is “abc”, with the length of 3.
Example 2:
Input: “bbbbb”
Output: 1
Explanation: The answer is “b”, with the length of 1.
Example 3:
Input: “pwwkew”
Output: 3
Explanation: The answer is “wke”, with the length of 3.
Note that the answer must be a substring, “pwke” is a subsequence and not a substring.

python解答

  • 思路一:暴力排序,从index=0开始寻找不重复的子字符串,当发现list中有相同字符时输出list的长度,一直循环到index=length(nums)-1,取程度最大的为输出。
    时间复杂度为O(n^2)
暴力遍历,双循环
        length = len(s)
        j = 0
        max1 = 0
        dict_1 = []
        for i in range(length):
            dict_1 = []
            j = 0
            for k in range(i, length):
                if s[k] in dict_1:
                    break
                j += 1
                dict_1.append(s[k])
            max1 = max(j, max1)
        return max1
  • 思路二:利用队列的思想,将字符串push进队列,遇到相同的字符时判断子字符串的长度,如果大于最大长度则更新最大长度,将相同字符和之前的字符都弹出队列之后继续循环加字符到队列中。
  • 时间复杂度为O(n)
 stack = []
        far = 0
        for i in range(len(s)):
            if s[i] in stack:
                length = len(stack)
                far = max(far, length)
                while s[i] in stack:
                    stack.pop(0)
            stack.append(s[i])
        length = len(stack)
        far = max(far, length)
        return far
  • 思路三: 在思路二的基础上,弹出队列的形式改为直接截断,耗时减少挺多。
stack = []
        far = 0
        for i in range(len(s)):
            if s[i] in stack:
                length = len(stack)
                far = max(far, length)
                begin = stack.index(s[i])
                stack = stack[begin+1:]
            stack.append(s[i])
        length = len(stack)
        far = max(far, length)
        return far

409. Longest Palindrome

Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.
This is case sensitive, for example “Aa” is not considered a palindrome here.
Note:
Assume the length of given string will not exceed 1,010.
Example:
Input:
“abccccdd”
Output:
7
Explanation:
One longest palindrome that can be built is “dccaccd”, whose length is 7.

  • 思路一:利用harsh表先存入所有的字符,当出现偶数个字符时,增加所有字符的长度,当出现奇数个字符时,flag变为1,再增加字符长度-1,最后返回值为length+flag
		length = 0
        flag = 0
        harsh = dict()
        for i in range(len(s)):
            if s[i] in harsh:
                harsh[s[i]] += 1
            else:
                harsh[s[i]] = 1
        # print(harsh)
        for char in harsh:
            if harsh[char] % 2 == 0:
                length += harsh[char]
            else:
                length += (harsh[char] - 1) 
                flag = 1
        return length + flag
  • 思路二:利用set,不断遍历原始字符串,当set中有相同字符时,说明肯定是成双出现的,此时长度加2;当set中没有相同字符时,将字符假如set中,最后成双的字符肯定都弹出了,如果set中还有字符的话肯定时单个的,所有当set长度不为0时最后的长度+1。
 		lists = set()
        num = 0
        for e in s:
            if e in lists:
                num += 2
                lists.remove(e)
            else:
                lists.add(e)
        if len(lists) > 0:
            return num + 1
        return num

290. Word Pattern

Given a pattern and a string str, find if str follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.
Example 1:
Input: pattern = “abba”, str = “dog cat cat dog”
Output: true
Example 2:
Input:pattern = “abba”, str = “dog cat cat fish”
Output: false
Example 3:
Input: pattern = “aaaa”, str = “dog cat cat dog”
Output: false
Example 4:
Input: pattern = “abba”, str = “dog dog dog dog”
Output: false
Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.

  • 思路一: python 解答: 利用harsh表,将pattern与lists一一对应,每个pattern 只会对应一个lists中的元素,如果harsh表中有pattern且lists对应的元素和harsh表中的不一致时则返回False,否则返回True.
        harsh = {}
        lists1 = []
        lists = str.split(' ')
        if len(lists) != len(pattern):
            return False
        if len(lists) == 1:
            lists = lists[0]
        for i in range(len(pattern)):
            if pattern[i] in harsh:
                if lists[i] != harsh[pattern[i]]:
                    return False
            else:
                if lists[i] in lists1:
                    return False
                lists1.append(lists[i])
                harsh[pattern[i]] = lists[i]
        return True
  • 思路二:利用python的set和zip函数,假设pattern和str都是一一对应的,则他们的长度都会相等,否则就有多种搭配的可能。这种方法的时间复杂度比思路一还慢,但是思路很好。
        str1 = str.split(' ')
        if len(str1) != len(pattern):
            return False
        return len(set(zip(list(pattern), str1))) == len(set(pattern)) == len(set(str1))

49. Group Anagrams

Given an array of strings, group anagrams together.
Example:
Input: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”],
Output:
[
[“ate”,“eat”,“tea”],
[“nat”,“tan”],
[“bat”]
]
Note:
All inputs will be in lowercase.
The order of your output does not matter.

python 解答:

  • 思路: 对strs中的元素进行字符串排序,排序相同的说明是同一个字符串,将同一个字符串放入字典的相同索引当中组成list,之后利用dict.values将所有的结果返回为list。
class Solution(object):
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        dicts = {}
        for str1 in strs:
            lists = list(str1)
            lists.sort()
            if str(lists) not in dicts:
                dicts[str(lists)] = []
            dicts[str(lists)].append(str1)
        return list(dicts.values())

187. Repeated DNA Sequences

All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: “ACGAATTCCG”. When studying DNA, it is sometimes useful to identify repeated sequences within the DNA.
Write a function to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule.
Example:
Input: s = “AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT”
Output: [“AAAAACCCCC”, “CCCCCAAAAA”]

  • 思路:建立一个字典,将所有的10个的字符串作为键值,数量作为value存入字典当中;遍历字典,value大于等于2的说明是重复的子序列。复杂度为O(n)
        harsh = dict()
        for i in range(len(s)):
            str1 = s[i:i+10]
            if str1 in harsh:
                harsh[str1] += 1
            else:
                harsh[str1] = 1
        lists = []
        for i in harsh:
            if harsh[i] > 1:
                lists.append(i)
        return lists
  • 思路二: 类似于思路一,采用的是python的set集合,发现运行时间减慢了4倍,看来set的操作复杂度比字典的高不少。
		harsh1 = set()
        harsh = set()
        for i in range(len(s)-9):
            print('a')
            str1 = s[i:i+10]
            if str1 in harsh1:
                harsh.add(str1)
            else:
                harsh1.add(str1)
        return list(harsh)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值