当前位置:网站首页>The simple problem of leetcode is to judge whether the number count of a number is equal to the value of the number

The simple problem of leetcode is to judge whether the number count of a number is equal to the value of the number

2022-07-07 08:09:00 ·Starry Sea

subject

I'll give you a subscript from 0 Start length is n String num , It contains only numbers .

If for Every 0 <= i < n The subscript i , All meet the digit i stay num In the num[i] Time , So please go back to true , Otherwise return to false .

Example 1:

Input :num = “1210”
Output :true
explain :
num[0] = ‘1’ . Numbers 0 stay num There's a time when .
num[1] = ‘2’ . Numbers 1 stay num There were two times in .
num[2] = ‘1’ . Numbers 2 stay num There's a time when .
num[3] = ‘0’ . Numbers 3 stay num There are zero occurrences in .
“1210” Meet the requirements of the topic , So back true .
Example 2:

Input :num = “030”
Output :false
explain :
num[0] = ‘0’ . Numbers 0 There should be 0 Time , But in num There's a time when .
num[1] = ‘3’ . Numbers 1 There should be 3 Time , But in num There are zero occurrences in .
num[2] = ‘0’ . Numbers 2 stay num In the 0 Time .
Subscript 0 and 1 Have violated the title requirements , So back false .

Tips :

n == num.length
1 <= n <= 10
num Numbers only .

source : Power button (LeetCode)

Their thinking

   According to the meaning of the topic , First, you need to find the frequency of each number in the string , Then traverse the entire string to check whether each element meets the conditions .

class Solution:
    def digitCount(self, num: str) -> bool:
        return all([str(Counter(num)[str(i)])==num[i] for i in range(len(num))])

 Insert picture description here

原网站

版权声明
本文为[·Starry Sea]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207070446576430.html