网站建设后怎么,手机网页制作html,WordPress page filed,网站用哪些系统做的好处找出字符串中第一个匹配项的下标、求解方程----2023/5/2
给你两个字符串 haystack 和 needle #xff0c;请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标#xff08;下标从 0 开始#xff09;。如果 needle 不是 haystack 的一部分#xff0c;则返回 -1…找出字符串中第一个匹配项的下标、求解方程----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:indexlen(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 x5-3x6x-2
输出: x2示例2
输入: equation xx
输出: Infinite solutions示例3
输入: equation 2xx
输出: x0提示: 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 solutionselse:return No solutionif x ! 0 and nums 0:return x0return fx{nums//x}来源力扣LeetCode 链接https://leetcode.cn/problems/solve-the-equation 著作权归领扣网络所有。商业转载请联系官方授权非商业转载请注明出处。