返回介绍

solution / 2000-2099 / 2053.Kth Distinct String in an Array / README_EN

发布于 2024-06-17 01:03:11 字数 3848 浏览 0 评论 0 收藏 0

2053. Kth Distinct String in an Array

中文文档

Description

A distinct string is a string that is present only once in an array.

Given an array of strings arr, and an integer k, return _the _kth_ distinct string present in _arr. If there are fewer than k distinct strings, return _an empty string _"".

Note that the strings are considered in the order in which they appear in the array.

 

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.

Solutions

Solution 1

class Solution:
  def kthDistinct(self, arr: List[str], k: int) -> str:
    counter = Counter(arr)
    for v in arr:
      if counter[v] == 1:
        k -= 1
        if k == 0:
          return v
    return ''
class Solution {
  public String kthDistinct(String[] arr, int k) {
    Map<String, Integer> counter = new HashMap<>();
    for (String v : arr) {
      counter.put(v, counter.getOrDefault(v, 0) + 1);
    }
    for (String v : arr) {
      if (counter.get(v) == 1) {
        --k;
        if (k == 0) {
          return v;
        }
      }
    }
    return "";
  }
}
class Solution {
public:
  string kthDistinct(vector<string>& arr, int k) {
    unordered_map<string, int> counter;
    for (auto& v : arr) ++counter[v];
    for (auto& v : arr) {
      if (counter[v] == 1) {
        --k;
        if (k == 0) return v;
      }
    }
    return "";
  }
};
func kthDistinct(arr []string, k int) string {
  counter := make(map[string]int)
  for _, v := range arr {
    counter[v]++
  }
  for _, v := range arr {
    if counter[v] == 1 {
      k--
      if k == 0 {
        return v
      }
    }
  }
  return ""
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文