![](https://img-blog.csdnimg.cn/20201014180756927.png?x-oss-process=image/resize,m_fixed,h_64,w_64)
Leetcode 字符串
文章平均质量分 66
Leetcode中与字符串相关的题目
努利!奋斗!
这个作者很懒,什么都没留下…
展开
-
Leetcode 1087. Brace Expansion
题目Descriptionhttps://leetcode.com/problems/brace-expansion/You are given a string s representing a list of words. Each letter in the word has one or more options.If there is one option, the letter is represented as is.If there is more than one option,原创 2022-05-15 07:50:44 · 222 阅读 · 0 评论 -
Leetcode 2224. Minimum Number of Operations to Convert Time
题目解法:class Solution {public: string largestGoodInteger(string num) { if(num.size() < 3) return ""; string ans = ""; for(int i=0;i<num.size()-2;i++){ string curr = num.substr(i,3); if(curr[0] ==原创 2022-05-15 01:47:02 · 47 阅读 · 0 评论 -
Leetcode 2266. Count Number of Texts
题目解法1:暴力recursion暴力recursion只能过一个test case,因为时间复杂度是O(2^n),n是数字串的长度class Solution {public: int dfs(string digits,unordered_map<char,string>& mapping){ if(digits.size() == 0) return 1; int res = 0; int i = 0;原创 2022-05-10 01:39:25 · 170 阅读 · 0 评论 -
Leetcode 472. Concatenated Words
题目解法:利用word break解法即可注意:c++在写的时候,这个参数一定要传引用,不然会占据很大的时间,比如下面的unordered_map<string,bool> &d,如果不传引用会tle像这边的d可以直接用unordered_set, unordered_set s(words.begin(), words.end());class Solution {public: bool canBreak(string s,unordered_map<原创 2022-05-05 12:20:45 · 706 阅读 · 0 评论 -
Leetcode 214. Shortest Palindrome
题目解法1:第一种解法是直接找到从这个字符串开始往后的最长回文子字符串,然后剩下的子字符串直接reverse之后加到前面就可以了class Solution: def shortestPalindrome(self, s: str) -> str: n = len(s) end = 0 for i in range(n+1): if s[:i] == s[:i][::-1]: end原创 2022-01-25 12:03:03 · 223 阅读 · 0 评论 -
KMP算法简介-string匹配
KMP算法简介KMP算法是用来做字符串匹配的,比如目标字符串:'acabacacd’是否能在源字符串:'acfacabacabacacdkacfacabacabacacdk’找到匹配。传统的暴力解法复杂度是O(nk)的,k是目标字符串长度,n是源字符串长度。所以有优化的KMP算法复杂度为O(n)算法核心这种算法的核心在于如何处理某个字符不match的情况。对于传统暴力算法,当某个位置字符不match的时候,就会往下顺移一位,这也是为什么暴力算法的复杂度是O(nk)。而KMP在某个位置字符不match的原创 2022-01-25 11:55:25 · 493 阅读 · 0 评论 -
Leetcode 387. First Unique Character in a String (cpp)
题目解法class Solution {public: int firstUniqChar(string s) { vector<pair<int,int>> count(26,{0,0}); for(int i=0;i<s.size();i++){ count[s[i] - 'a'].second += 1; count[s[i] - 'a'].first = i;原创 2021-01-13 07:52:18 · 117 阅读 · 0 评论 -
Leetcode 49. Group Anagrams (python+cpp)
题目解法1:字符串排序对每个字符串排序,anagram会有相同的排序结果,所以可以用排序后的字符串作为hashmap的keypython版本:对于python版本,字符串不能直接call sort函数,必须要用sorted返回一个list,而且list不能作为字典的key,而必须转换成tupleclass Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: dic = coll原创 2021-01-04 04:32:24 · 248 阅读 · 1 评论 -
Leetcode 20. Valid Parentheses (cpp)
题目解法:stack繁琐的写法class Solution {public: bool isValid(string s) { if(s.size() % 2 != 0) return false; stack<char> st; for(auto c:s){ if(c == '(' || c == '[' || c == '{'){ st.push(c);原创 2020-12-27 09:48:27 · 88 阅读 · 1 评论 -
Leetcode Longest Substring Without Repeating Characters (cpp)
题目解法1:sliding window利用滑动窗口,使得窗口内始终不包含重复元素顺序移动右边界,如果右边界所指元素已经在窗口出现,那么移动做指针知道右边界所指元素被移出窗口现在窗口内已经不包含右边界所指元素,更新右边界所指元素的出现次数,并且更新最大长度需要注意这边有符号和空格,所以要注意其他符号的ASCII值class Solution {public: int lengthOfLongestSubstring(string s) { vector<in原创 2020-12-25 07:10:47 · 82 阅读 · 0 评论 -
Leetcode wordbreak类型的序列问题
题目1:139. Word Break解法1:暴力backtrackingclass Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: def backtracking(start): nonlocal ans if start == len(s): ans = True原创 2020-12-05 05:48:25 · 211 阅读 · 0 评论 -
Leetcode 1405. Longest Happy String (python)
题目解法贪心思想。每次取个数最多的来加,同时判断前两个是否相同。利用最大堆保持顺序。class Solution: def longestDiverseString(self, a: int, b: int, c: int) -> str: # main idea: use a greedy approach. Every time, try to take one char from the category with the maximum count. And u原创 2020-12-01 10:35:19 · 289 阅读 · 0 评论 -
1419. Minimum Number of Frogs Croaking (python)
题目解法:这个题目有点意思的,比较巧妙。我们需要找的是,这五个字母在某个时间出现的最大次数。限制条件是,每当遇到一个k的时候,放掉一只青蛙。同时需要检查给的字符串是不是无效,依照两个规则判断:如果出现了一个字符,但是应该出现在他之前的字符没有出现,比如直接来个r,那就无效当所有过程结束,所有的字符应该要刚好形成完整的若干个croak接下来的就是实现问题了class Solution: def minNumberOfFrogs(self, croakOfFrogs: str) -&原创 2020-11-27 12:27:52 · 288 阅读 · 0 评论 -
Leetcode 1456. Maximum Number of Vowels in a Substring of Given Length (python)
题目解法1:stackclass Solution: def maxVowels(self, s: str, k: int) -> int: if len(s)<k: return 0 candidates = ['a','e','i','o','u'] ans = 0 window = collections.deque() for c in s[:k]:原创 2020-11-19 10:56:34 · 253 阅读 · 0 评论 -
Leetcode 1487. Making File Names Unique (python)
题目解法1:暴力TLEclass Solution: def getFolderNames(self, names: List[str]) -> List[str]: seen = {} ans = [] for name in names: if name not in seen: ans.append(name) seen[name] = True原创 2020-11-12 09:29:14 · 267 阅读 · 2 评论 -
Leetcode 1529. Bulb Switcher IV (python)
题目解法:每次有连续的两个字符不同就需要一次反转class Solution: def minFlips(self, target: str) -> int: if not target: return 0 if target[0] == '0': count = 0 else: count = 1 for i in range(1,len(targe原创 2020-11-05 07:07:23 · 140 阅读 · 0 评论 -
Leetcode 44. Wildcard Matching & Regular Expression Matching (python)
Leetcode 44. Wildcard Matching解法:动态规划这道题目在于理解代码中的step2和step4的第一部分关于step 4的第一步份,实际上可以用0,1背包跟完全背包之前的关系来理解class Solution {public: bool isMatch(string s, string p) { int sl = s.length(); int pl = p.length(); // step1:原创 2020-10-29 13:48:23 · 142 阅读 · 0 评论 -
Leetcode 1562. Find Latest Group of Size M (python)
Leetcode 1562. Find Latest Group of Size M题目解法1:TLE解法2:题目解法1:TLE自己开始想出来的非常复杂的解法,还是TLE了,主要T在从list里面删除元素class Solution: def findLatestStep(self, arr: List[int], m: int) -> int: ans = -1 pos2len = {} len2pos = collections.d原创 2020-10-28 12:37:24 · 233 阅读 · 0 评论 -
Leetcode 1578. Minimum Deletion Cost to Avoid Repeating Letters (python)
Leetcode 1578. Minimum Deletion Cost to Avoid Repeating Letters题目解法1:one pass解法题目解法1:略复杂版本的解法,一开始在contest的时候写的版本class Solution: def minCost(self, s: str, cost: List[int]) -> int: prefix = [0]*(len(cost)+1) tmp = 0 for i,原创 2020-10-23 04:37:35 · 475 阅读 · 0 评论 -
Leetcode 1616. Split Two Strings to Make Palindrome (python+cpp)
Leetcode 1616. Split Two Strings to Make Palindrome题目:解法1:暴力,TLE解法2:O(n)题目:解法1:暴力,TLEclass Solution: def checkPalindromeFormation(self, a: str, b: str) -> bool: if len(a) == 1 or len(b) == 1: return True n = len(a)原创 2020-10-21 13:45:58 · 193 阅读 · 0 评论 -
Leetcode 1593. Split a String Into the Max Number of Unique Substrings(python)
Leetcode 1593. Split a String Into the Max Number of Unique Substrings题目解法:暴力backtracking题目解法:暴力backtracking因为要unique,所以dp不太做得了class Solution: def maxUniqueSplit(self, s: str) -> int: def backtracking(ind): nonlocal ans原创 2020-10-12 07:50:58 · 223 阅读 · 0 评论 -
Leetcode 22. Generate Parentheses (python)
Leetcode 22. Generate Parentheses题目解法:backtrackingfollow up题目解法:backtrackingclass Solution: def generateParenthesis(self, n: int) -> List[str]: def backtracking(comb,left,right): # if left==right, means one valid combination原创 2020-10-09 13:50:19 · 376 阅读 · 0 评论 -
Leetcode 32. Longest Valid Parentheses (python+cpp)
Leetcode 32. Longest Valid Parentheses题目解法1:stack解法2:两次扫描题目解法1:stack解释参见commentclass Solution: def longestValidParentheses(self, s: str) -> int: # add -1 as the starting of a valid sequence stack = [-1] max_length = 0原创 2020-10-09 13:47:34 · 141 阅读 · 0 评论 -
格式化print括号与字符
题目解法:设计一个counter,遇到{加一,遇到}减一,根据counter值来控制每个位置的缩进def print_string(s): count = 0 curr_s = '' for i in range(len(s)): v = s[i] if v=='{': print(' '*count+'{') count+=1 if ord(v)>=ord('a') and原创 2020-10-03 01:00:28 · 109 阅读 · 0 评论 -
Leetcode 394. Decode String (python)
Leetcode 394. Decode String题目解法1:recursion解法2:stack - one pass题目这道题应该跟basic calculator的题目合起来看,本质上是一样的解法1:recursion这里用了一个trick,函数返回值中包含一个index,这样就可以保证我们check到下一层递归处理到的位置class Solution: def decodeString(self, s: str) -> str: def decode(i原创 2020-10-02 04:08:11 · 541 阅读 · 1 评论 -
Leetcode 520. Detect Capital (python+cpp)
题目解法:只需要注意一下python里面is_upper的用法即可。C++里面直接进行比较就好python版本class Solution: def detectCapitalUse(self, word: str) -> bool: capital_pos = [] for i,c in enumerate(word): if c.isupper(): capital_pos.append(i)原创 2020-09-30 09:55:55 · 164 阅读 · 0 评论 -
Leetcode 140. Word Break II (python+cpp)
Leetcode 140. Word Break II题目解法1:动态规划+暴力递归解法2:recursion+memorization总结题目解法1:动态规划+暴力递归首先用word break I的方法来判断是否能够拆分能拆分之后,暴力recursion解出所有答案class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> List[str]: def check(s):原创 2020-09-30 09:46:13 · 430 阅读 · 0 评论 -
Leetcode 269. Alien Dictionary(python)
Leetcode 269. Alien Dictionary题目解法:拓扑排序题目解法:拓扑排序这道题的解法leetcode官方写的非常好,也非常有助于理解拓扑排序,建议仔仔细细地看他的官方解析class Solution: def alienOrder(self, words: List[str]) -> str: # create adject matrx of the graph adj_list = collections.defaultdic原创 2020-09-26 07:25:47 · 2373 阅读 · 0 评论 -
Leetcode 43. Multiply Strings (python+cpp)
Leetcode 43. Multiply Strings题目解法:题目解法:class Solution: def multiply(self, num1: str, num2: str) -> str: if num1=='0' or num2=='0': return '0' product = [0]*(len(num1)+len(num2)) pos = len(product)-1原创 2020-09-26 06:12:01 · 206 阅读 · 0 评论 -
string的加/减/乘 (python)
题目描述以string表示的两个数字,求他们的加/减/乘,最后结果以string返回加法:def add_string(num1, num2): ans = '' carry = 0 p1 = len(num1) - 1 p2 = len(num2) - 1 while p1>=0 or p2>=0: v1 = ord(num1[p1]) - ord('0') if p1 >= 0 else 0 v2 = or原创 2020-09-26 06:07:29 · 1654 阅读 · 0 评论 -
Leetcode 415. Add Strings (python+cpp)
Leetcode 415. Add Strings题目解法:follow up 1:两个string相减follow up2:两个string相加,但是有可能有负号题目解法:这边默认肯定是不能用强制类型转换的python:class Solution: def addStrings(self, num1: str, num2: str) -> str: ans = '' pt1 = len(num1)-1 pt2 = len(num2原创 2020-09-23 07:53:04 · 250 阅读 · 0 评论 -
Leetcode 28. Implement strStr() (python+cpp)
Leetcode 28. Implement strStr题目解法:题目解法:brutal in python:class Solution: def strStr(self, haystack: str, needle: str) -> int: if not needle: return 0 n = len(needle) for i in range(len(haysta原创 2020-07-15 08:24:26 · 109 阅读 · 0 评论 -
Leetcode Basic Calculator I,II,III (python+cpp)
Leetcode 227. Basic Calculator II题目解析:题目解析:这个是必须掌握的题目。总体思路是,利用栈保存临时运算的结果,高优先级的先运算,最后直接对栈一次性求和。具体策略是:利用栈来临时储存之前的运算结果,利用pre_op来保存之前最近一个的操作符,利用num保存当前数字首先初始化stack为空,pre_op为+,num为0如果当前碰到的是数字,要跟之前保存的数字进行累加,这是为了应对多位数的出现如果当前碰到的是操作符或者是到了最后一个位置,那么对pre_op进行原创 2020-07-14 11:38:32 · 703 阅读 · 0 评论 -
Leetcode 696. Count Binary Substrings (python+cpp)
Leetcode 696. Count Binary Substrings题目解析:题目解析:题目的意思是,所有的binary子串中,0和1的个数相同的有几个。这道题目leetcode官方的解析很清楚,这边引用一下:We can convert the string s into an array groups that represents the length of same-character contiguous blocks within the string. For example,原创 2020-07-14 10:55:01 · 167 阅读 · 0 评论 -
Leetcode 647. Palindromic Substrings (python+cpp)
Leetcode 647. Palindromic Substrings题目解析题目解析虽然这是个medium,但是其实思路很清晰。回文的关键特征就是从中心对称。根据这个特性,可以从中心点出发,向两边扩散寻找。具体步骤为,找到字符组中所有可能作为中心的位置,然后找出以这个位置为中心的所有可能回文串。值得注意的是,回文字符串的中心可能是某个字符的位置,也可能是两个字符中间的位置。换句话说,可能回文字符串的长度是偶数,也可能是奇数。python:class Solution: def cou原创 2020-07-14 10:49:38 · 116 阅读 · 0 评论 -
Leetcode 205. Isomorphic Strings (python+cpp)
Leetcode 205. Isomorphic Strings题目解析:题目解析:同构的定义是,可以通过把一个字符串的某些相同的字符转换成另一些相同的字符,使得两个字符串相同,且两种不同的字符不能够被转换成同一种字符。可以建立一个字典,记录字符出现的位置。两个字符串中,有对应转换关系的字符必须在同一位置,否则两个字符串不同构。python:python解法这边要注意最后return的时候,我们前面的操作只保证了对于s中不同的字符,与t中的字符有相同位置的对应关系,但这只能保证s到t是正确的原创 2020-07-13 12:47:51 · 275 阅读 · 0 评论 -
Leetcode 242. Valid Anagram (python+cpp)
Leetcode 242. Valid Anagram题目解析:题目解析:python:class Solution: def isAnagram(self, s: str, t: str) -> bool: if len(s) != len(t): return False counts = collections.defaultdict(int) for i in rang原创 2020-07-13 12:27:23 · 151 阅读 · 0 评论