Re: [闲聊] 每日leetcode

楼主: sustainer123 (caster)   2024-08-05 08:50:42
https://leetcode.com/problems/kth-distinct-string-in-an-array
2053. Kth Distinct String in an Array
distinct string代表此字串在该阵列中只出现一次
给定阵列arr跟数字k 请回传第k个distinct string
如果 distinct string < k 回传空字串
Example 1:
Input: arr = ["d","b","c","b","c","a"], k = 2
Output: "a"
Explanation:
The only distinct strings in arr are "d" and "a".
"d" appears 1st, so it is the 1st distinct string.
"a" appears 2nd, so it is the 2nd distinct string.
Since k == 2, "a" is returned.
Example 2:
Input: arr = ["aaa","aa","a"], k = 1
Output: "aaa"
Explanation:
All strings in arr are distinct, so the 1st string "aaa" is returned.
Example 3:
Input: arr = ["a","b","a"], k = 3
Output: ""
Explanation:
The only distinct string is "b". Since there are fewer than 3 distinct
strings, we return an empty string "".
Constraints:
1 <= k <= arr.length <= 1000
1 <= arr[i].length <= 5
arr[i] consists of lowercase English letters.
思路:
哈希表记数
然后把出现次数 == 1的数字放进新阵列
最后确认长度回传答案 end
Python Code:
class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
record = defaultdict(int)
for c in arr:
record[c] += 1
distinct = [k for k,v in record.items() if v == 1]
if k > len(distinct):
return ""
else:
return distinct[k-1]

Links booklink

Contact Us: admin [ a t ] ucptt.com