dart 函数,该函数将打印单词列表中可以出现的最少字母数

bqucvtff  于 2023-11-14  发布在  其他
关注(0)|答案(1)|浏览(127)

我需要一个 dart 函数,它将打印所有给定单词中可能存在的最小字母数。假设单词是“apple,table,rum,bread”。该函数应打印“a”和“r”。让我来解释一下。正如你所看到的三个单词(apple,table,bread)有共同的字母(a,e),该函数应该打印a或e。另一方面,“rum”我没有在其他单词中常见的字母,所以函数应该打印“r”或“u”或“m”。如果你需要任何进一步的解释,请让我知道。谢谢
尝试了下面的代码,但它正在打印“没有常用字母”。

void findCommonLetters(List<String> words) {
      if (words.isEmpty) {
        print("No common letters.");
        return;
      }
    
      Set<String> commonLetters = Set.from(words[0].split(''));
    
      for (int i = 1; i < words.length; i++) {
        final word = words[i];
        final wordLetters = Set.from(word.split(''));
    
        commonLetters = commonLetters.intersection(wordLetters);
      }
    
      if (commonLetters.isEmpty) {
        print("No common letters.");
      } else {
        print("Common letters: ${commonLetters.join(", ")}");
      }
    }
    
    void main() {
      List<String> words = ["apple", "banana", "sun"];
      findCommonLetters(words);
    }

字符串

w1jd8yoj

w1jd8yoj1#

我认为你的函数没有做你期望的事情。在apple,banana和sun之间没有共同的字母。这就是你要检查的
commonLetters的值变化如下:

// before the loop
['a','p','l','e']
// in the first loop iteration, ['a','p','l','e'] intersected with ['b','a','n']
['a']
// in the second loop iteration, ['a'] intersected with ['s','u','n']
[]

字符串
在您最初的示例['apple', 'table', 'bread']中,您的函数工作得很好:

Common letters: a, e

比较所有单词

相反,如果你想查看集合中每个单词组合之间的常用字母,你可以尝试循环每一对并在那里进行比较。

void findCommonLetters(List<String> words) {
  if (words.isEmpty) {
    print("No common letters.");
    return;
  }
  
  Set<String> commonLetters = {};
  for (int i = 0; i < words.length; i++) {
    Set<String> iLetters = Set.from(words[i].split(''));
    // we only need to compare 1 way, so we can start at i+1
    for (int j = i+1; j < words.length; j++) {
      Set<String> jLetters = Set.from(words[j].split(''));
      
      // compare word i and word j, and store their common letters
      commonLetters.addAll(iLetters.intersection(jLetters).toList());
    }
  }
  
  if (commonLetters.isEmpty) {
    print("No common letters.");
  } else {
    print("Common letters: ${commonLetters.join(", ")}");
  }
}

void main() {
  List<String> words = ["apple", "banana", "sun"];
  findCommonLetters(words);
}


所以问题是,你期望什么?如果你想找到一个集合中 * 所有 * 单词之间的常用字母,恭喜你,你已经做到了:p
否则,您可以查看上面的代码来比较集合中的 * 每对 * 单词。

Common letters: a, l, e, b


对于["apple", "banana", "sun"],这将返回

Common letters: a, n

相关问题