原文:

给定一个由小写字母和整数组成的 s ,任务是打印字符串 s 中出现 k 次的所有单词。

示例:

输入: s =“香蕉是黄色的,太阳花也是黄色的”,k = 2 输出:“是”“黄色的”“在” 解释:单词“是”“黄色的”“在”在字符串中出现两次。

输入: s =“极客为极客”,k = 2 输出:“极客”

方法:按照以下步骤解决问题:

  • 初始化一个 l 来存储字符串中出现的单词。
  • 单词并存储在列表中。
  • ,对于每个单词:
    • 如果发现单词的频率为 k :
      • 把那个字打印出来。
      • 从列表中删除该单词当前出现的位置。

下面是上述方法的实现:

c

// cpp program for the above approach
#include
using namespace std;
// function to print all the words
// occurring k times in a string
void kfreqwords(string s, int k)
{
  // stores the words
  string temp = "";
  vector l;
  for (auto x: s)
  {
    if(x == ' ')
    {
      l.push_back(temp);
      temp = "";
    }
    else
      temp  = x;
  }
  // traverse the list
  for (auto x: l)
  {
    // check for count
    if (count(l.begin(), l.end(), x) == k)
    {
      // print the word
      cout << x << endl;
      // remove from list
      remove(l.begin(),l.end(), x);
    }
  }
}
// driver code
int main()
{
  // given string
  string s = "banana is in yellow and sun flower is also in yellow ";
  // given value of k
  int k = 2;
  // function call to find
  // all words occurring k times
  kfreqwords(s, k);
}
// this code is contributed by surendra_gangwar.

python 3

# python3 program for the above approach
# function to print all the words
# occurring k times in a string
def kfreqwords(s, k):
    # stores the words
    l = list(s.split(" "))
    # traverse the list
    for i in l:
        # check for count
        if l.count(i) == k:
            # print the word
            print(i)
            # remove from list
            l.remove(i)
# driver code
if __name__ == "__main__":
    # given string
    s = "banana is in yellow and sun flower is also in yellow"
    # given value of k
    k = 2
    # function call to find
    # all words occurring k times
    kfreqwords(s, k)

output

is
yellow
in

时间复杂度:o(n) t5辅助空间:** o(1)

方法 2:使用内置的 python 函数:

  • 因为一个句子中的所有单词都用空格隔开。
  • 我们必须用 split()将句子用空格分开。
  • 我们将所有的单词用空格分开,并存储在一个列表中。
  • 使用计数器功能统计单词的出现频率
  • 遍历频率字典,打印频率为 k 的单词

下面是上述方法的实现:

python 3

# python program for the above approach
from collections import counter
# python program to print words
# which occurs k times
def printwords(sentence, k):
    # splitting the string
    lis = list(sentence.split(" "))
    # calculating frequency of every word
    frequency = counter(lis)
    # traversing the frequency
    for i in frequency:
        # checking if frequency is k
        if(frequency[i] == k):
            # print the word
            print(i, end=" ")
# driver code
# given string
sentence = "sky is blue and my favourite color is blue"
# given value of k
k = 2
printwords(sentence, k)
# this code is contributed by vikkycirus

java 描述语言


输出:

is blue 

时间复杂度: o(n)

空间复杂度: o(n)