1796. 字符串中第二大的数字
给你一个混合字符串 s ,请你返回s中第二大的数字,如果不存在第二大的数字,请你返回 -1 。
混合字符串由小写英文字母和数字组成。
此题用暴力法解决有两种思路:
方法1:
class Solution(object):
def secondHighest(self, s):
res=list(s)
ans=[]
num=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
for i in num:
if i in num and i in res:
ans.append(i)
ans1=[i for i in res if (i not in ans)]
ans2=list(set(ans1))
ans2.sort(reverse=True)
#print(ans2)
return int(ans2[1]) if len(ans2)>=2 else -1
此题中,想直接在res上将存在于num中的值进行移除,开始想使用remove,发现for循环中尽量不要使用remove操作,因为在遍历过程中删除某个元素之后,会将它后面的元素向前移动一位,而for循环是继续遍历下一个位置的,所以遍历过程中会有遗漏。
因此最终使用了给一个空列表进行append的方式来替代remove的作用。
方法2:
class Solution:
def secondHighest(self, s: str) -> int:
res=[]
num=["1","2","3","4","5","6","7","8","9","0"]
for i in s:
if i in num and int(i) not in res:
res.append(int(i))
else:
pass
res.sort(reverse=True)
return res[1] if len(res)>=2 else -1