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

huangapple go评论81阅读模式
英文:

Comparing LinkedList Elements to String in Java

问题

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

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

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

    int count = 0;              
    for (String word : list) {
            for (int i = 0; i < str.length(); i++){
                    while (count != n) {
                           if (word.contains("" + str.charAt(i))){
                                count ++;
                            }
                            if (count != n) {
                                list.remove(word);
                            }
                        }
                    }
             }
英文:

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.

    int count = 0;              
    for (String word : list) {
            for (int i = 0; i &lt; str.length(); i++){
                    while (count != n) {
                           if (word.contains(&quot;&quot; + str.charAt(i))){
                                count ++;
                            }
                            if (count != n) {
                                list.remove(word);
                            }
                        }
                    }
             }

答案1

得分: 1

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

for (String word : list)
{
    int count = 0; 
    for (int i = 0; i < str.length(); i++)
    {
        if (word.contains("" + str.charAt(i)))
        {
            count++;
        }
    }
    if (count != n)
    {
        list.remove(word);
    }
}
英文:

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

for (String word : list)
{
   int count = 0; 
   for (int i = 0; i &lt; str.length(); i++)
   {
        if (word.contains(&quot;&quot; + str.charAt(i)))
        {
           count ++;
        }
    }
    if (count != n)
    {
        list.remove(word);
    }
                        
   }
}

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

发表评论

匿名网友

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

确定