网站建设价位高有低seo网络推广软件
找出字符串中第一个匹配项的下标、求解方程----2023/5/2
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle 不是 haystack 的一部分,则返回 -1 。
示例1:
输入:haystack = "sadbutsad", needle = "sad"
输出:0
解释:"sad" 在下标 0 和 6 处匹配。
第一个匹配项的下标是 0 ,所以返回 0 。
示例 2:
输入:haystack = "leetcode", needle = "leeto"
输出:-1
解释:"leeto" 没有在 "leetcode" 中出现,所以返回 -1 。
题解:
class Solution:def strStr(self, haystack: str, needle: str) -> int:if len(haystack) == len(needle) and haystack == needle:return 0for index in range(len(haystack) - len(needle)+1):if haystack[index:index+len(needle)] == needle:return indexreturn -1
题解:KMP算法 参考
class Solution:def strStr(self, haystack: str, needle: str) -> int:n = len(haystack)m = len(needle)next = [0]k = 0for i in range(1, m):while k > 0 and needle[k] != needle[i]:k = next[k-1]if needle[k] == needle[i]:k += 1next.append(k)j = 0for i in range(n):while j > 0 and haystack[i] != needle[j]:j = next[j-1]if haystack[i] == needle[j]:j += 1if j == m:return i - j + 1return -1
提示:
1 <= haystack.length, needle.length <= 104
haystack 和 needle 仅由小写英文字符组成
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
求解一个给定的方程,将x以字符串 “x=#value” 的形式返回。该方程仅包含 ‘+’ , ‘-’ 操作,变量 x 和其对应系数。
如果方程没有解或存在的解不为整数,请返回 “No solution” 。如果方程有无限解,则返回 “Infinite solutions” 。
题目保证,如果方程中只有一个解,则 ‘x’ 的值是一个整数。
示例1:
输入: equation = "x+5-3+x=6+x-2"
输出: "x=2"
示例2:
输入: equation = "x=x"
输出: "Infinite solutions"
示例3:
输入: equation = "2x=x"
输出: "x=0"
提示:
3 <= equation.length <= 1000
equation 只有一个 ‘=’.
方程由绝对值在 [0, 100] 范围内且无任何前导零的整数和变量 ‘x’ 组成。
题解:
class Solution:def scanner(self, strs):x, nums = 0, 0len_strs = len(strs)if strs[0] == '-1':sign = -1else:sign = 1num = 0flag = -1for start in range(len_strs):if strs[start] == '-':nums += sign * numnum, mul = 0, 0sign = -1elif strs[start] == '+':nums += sign * numnum, mul = 0, 0sign = 1elif strs[start] == 'x':if num == 0:if flag == 0:x += 0else:x += 1 * signelse:x += sign * numnum, mul = 0, 0else:num = 10 * num + int(strs[start])if num == 0:flag = 0if num != 0:nums += sign * numreturn x, numsdef solveEquation(self, equation: str) -> str:left, right = equation.split("=")left_x, left_nums = self.scanner(left)right_x, right_nums = self.scanner(right)x = left_x - right_x nums = right_nums - left_numsif x == 0:if nums == 0:return "Infinite solutions"else:return "No solution"if x != 0 and nums == 0:return "x=0"return f"x={nums//x}"
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/solve-the-equation
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。