在Java中比较链表元素和字符串

huangapple 未分类评论53阅读模式
英文:

Comparing LinkedList Elements to String in Java

问题

我正在尝试编写一个程序,用于将链表中的字符串与单个字符串进行比较。我试图检查链表中的字符串是否恰好有某个数字:int n,在单个字符串中有相同的字母。

例如,如果链表中的第一个单词是"word"n = 2,单个字符串是"weed"。这些单词包含了2个相同的字母。所有其他不符合此条件的元素将从链表中删除。这些单词的长度也相同。

我已经编写了下面的代码,但我担心这可能不是实现这一目标的最佳方式,或者while循环会无限继续。

  1. int count = 0;
  2. for (String word : list) {
  3. for (int i = 0; i < str.length(); i++){
  4. while (count != n) {
  5. if (word.contains("" + str.charAt(i))){
  6. count ++;
  7. }
  8. if (count != n) {
  9. list.remove(word);
  10. }
  11. }
  12. }
  13. }
英文:

I am trying to write a program that compares the strings from a LinkedList to a single string. I am trying to check if the strings in the LinkedList have exactly some number: int n of the same letters in the single string.

For example, if the first word in the LinkedList is &quot;word&quot;, n = 2, and the single string was &quot;weed&quot;. These words contain 2 of the same letters. All other elements not following this would be removed from the LinkedList. These words are also the same size.

I have written the code below, but I'm worried that this not the best way to implement this, or the while loop will continue infinitely.

  1. int count = 0;
  2. for (String word : list) {
  3. for (int i = 0; i &lt; str.length(); i++){
  4. while (count != n) {
  5. if (word.contains(&quot;&quot; + str.charAt(i))){
  6. count ++;
  7. }
  8. if (count != n) {
  9. list.remove(word);
  10. }
  11. }
  12. }
  13. }

答案1

得分: 1

你根本不需要使用 while 循环来解决这个问题。以下代码应该可以工作。

  1. for (String word : list)
  2. {
  3. int count = 0;
  4. for (int i = 0; i < str.length(); i++)
  5. {
  6. if (word.contains("" + str.charAt(i)))
  7. {
  8. count++;
  9. }
  10. }
  11. if (count != n)
  12. {
  13. list.remove(word);
  14. }
  15. }
英文:

You do not need a while loop at all to solve this. This code should work.

  1. for (String word : list)
  2. {
  3. int count = 0;
  4. for (int i = 0; i &lt; str.length(); i++)
  5. {
  6. if (word.contains(&quot;&quot; + str.charAt(i)))
  7. {
  8. count ++;
  9. }
  10. }
  11. if (count != n)
  12. {
  13. list.remove(word);
  14. }
  15. }
  16. }

huangapple
  • 本文由 发表于 2020年4月8日 03:30:32
  • 转载请务必保留本文链接:https://java.coder-hub.com/61087965.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定