R2-字符串
目录
解简单方程法
线性代数法
ps:
就是从里面找出one,two,zero,---nine
想到哈希表,key代表单词,value代表0---9
用t表示单词,那不就是t在s中的查找问题了吗
但这样显然有些麻烦,在于t是不确定的,t需要遍历一遍keys(),然后再在s中查找,时间复杂度会比较高,应该超时。
解简单方程法
ben神
class Solution:
def originalDigits(self, s: str) -> str:
nums=["zero","one","two","three","four","five","six","seven","eight","nine"]
order=[(0,"z"),(2,"w"),(4,"u"),(5,"f"),(6,"x"),(7,"s"),(1,"o"),(8,"g"),(3,"h"),(9,"i")]
def reduce(num,v):
for c in nums[num]:
cnts[c]-=v
#返回字典代表每个字符的计数
cnts=Counter(s)
ret=[0]*10
for num,key in order:
#v代表字符串中特征字符的个数,num是要返回的数字,也作为下标
v=cnts[key]
reduce(num,v)
ret[num]=v
return "".join(str(i)*v for i,v in enumerate(ret))
线性代数法
. - 力扣(LeetCode)
class Solution:
def originalDigits(self, s: str) -> str:
cnt = Counter(s)
return "0" * cnt["z"] + \
"1" * (cnt["o"] - cnt["z"] - cnt["u"] - cnt["w"]) + \
"2" * cnt["w"] + \
"3" * (cnt["r"] - cnt["z"] - cnt["u"]) + \
"4" * cnt["u"] + \
"5" * (cnt["v"] - cnt["s"] + cnt["x"]) + \
"6" * cnt["x"] + \
"7" * (cnt["s"] - cnt["x"]) + \
"8" * (cnt["t"] - cnt["w"] - cnt["r"] + cnt["z"] + cnt["u"]) + \
"9" * ((cnt["n"] - cnt["s"] + cnt["x"] - cnt["o"] + cnt["z"] + cnt["u"] + cnt["w"]) // 2)
ps:
第2种还没看懂。稍后再说