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]