「这是我参与2022首次更文挑战的第9天,活动详情查看:2022首次更文挑战」
[字符串相加]
给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和并同样以字符串形式返回。
你不能使用任何內建的用于处理大整数的库(比如 BigInteger), 也不能直接将输入的字符串转换为整数形式。
示例 1:
输入:num1 = "11", num2 = "123" 输出:"134" 示例 2:
输入:num1 = "456", num2 = "77" 输出:"533" 示例 3:
输入:num1 = "0", num2 = "0" 输出:"0" 提示:
1 <= num1.length, num2.length <= 104 num1 和num2 都只包含数字 0-9 num1 和num2 都不包含任何前导零
分析过程: 1.双指针方法 2.先设置值m、n代表前后两个指针 3.进行while 判断,知道m>=0 or n>=0 为止
class Solution:
def addStrings(self, num1: str, num2: str) -> str:
res = ""
m, n, carry = len(num1) - 1, len(num2) - 1, 0
while m >= 0 or n >= 0:
n1 = int(num1[m]) if m >= 0 else 0
n2 = int(num2[n]) if n >= 0 else 0
tmp = n1 + n2 + carry
carry = tmp // 10
res = str(tmp % 10) + res
m, n = m - 1, n - 1
return "1" + res if carry else res
执行结果:
[最长回文串]
给定一个包含大写字母和小写字母的字符串 s ,返回 通过这些字母构造成的 最长的回文串 。
在构造过程中,请注意 区分大小写 。比如 "Aa" 不能当做一个回文字符串。
示例 1:
输入:s = "abccccdd" 输出:7 解释: 我们可以构造的最长的回文串是"dccaccd", 它的长度是 7。 示例 2:
输入:s = "a" 输入:1 示例 3:
输入:s = "bb" 输入: 2
提示:
1 <= s.length <= 2000 s 只能由小写和/或大写英文字母组成
解题过程: 1.字典方法 2.先用字典,将每个字母计算出来,存入dict中 3.遍历字典,进行判断
class Solution:
def longestPalindrome(self, s: str) -> int:
c_dict = {}
for row in s:
if row in c_dict:
c_dict[row] += 1
else:
c_dict[row] = 1
res = 0
has_odd = False
for k, v in c_dict.items():
if v % 2 == 0:
res += v
else:
res += v - 1
has_odd = True
if has_odd:
res += 1
return res
执行结果: