NikeDog
NikeDog

Reputation: 33

Comparing LinkedList Elements to String in Java

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 "word", n = 2, and the single string was "weed". 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 < str.length(); i++){
                    while (count != n) {
                           if (word.contains("" + str.charAt(i))){
                                count ++;
                            }
                            if (count != n) {
                                list.remove(word);
                            }
                        }
                    }
             }

Upvotes: 0

Views: 132

Answers (1)

Fatima Hojeij
Fatima Hojeij

Reputation: 73

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 < str.length(); i++)
   {
        if (word.contains("" + str.charAt(i)))
        {
           count ++;
        }
    }
    if (count != n)
    {
        list.remove(word);
    }

   }
}

Upvotes: 1

Related Questions