英文:
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 "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);
}
}
}
}
答案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 < str.length(); i++)
{
if (word.contains("" + str.charAt(i)))
{
count ++;
}
}
if (count != n)
{
list.remove(word);
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论