gpt4 book ai didi

java - 需要从 arraylist 中删除其中包含字母的字符串,如果包含其他则不要触摸

转载 作者:行者123 更新时间:2023-11-29 05:28:55 26 4
gpt4 key购买 nike

所以我想做一个方法修复来删除所有包含字母 r 的单词,然后将所有包含字母 l 的单词乘以 x2,然后如果单词中包含 rl,请不要触摸它。方法有效,但不是必须的。我认为它必须对 remove 做些什么。

public class Solution
{
public static void main(String[] args) throws Exception
{
BufferedReader bis = new BufferedReader(new InputStreamReader(System.in));

ArrayList<String> list = new ArrayList<String>();
list.add("rose"); //0
list.add("liar"); //1
list.add("lisa"); //2
list = fix(list);

for (String s : list)
{
System.out.println(s);
}
}

public static ArrayList<String> fix(ArrayList<String> list) {
//
ArrayList<String> temp = new ArrayList<String>();
for(int i = 0; i < list.size(); i++){
String s = list.get(i);

boolean strL = s.contains("l");
boolean strR = s.contains("r");

if(strR){
temp.remove(s);
}
if(strL && strR) {
temp.add(s);
} else {

if(strL) {
temp.add(s);
temp.add(s);
}
}

}
return temp;
}
}

最佳答案

你应该使用迭代器,以及异或 (^) 运算符。

public static ArrayList<String> fix(ArrayList<String> list) {
ArrayList<String> temp = new ArrayList<>();
for (Iterator<String> i = list.iterator(); i.hasNext();) {
String str = i.next();
boolean isL = str.contains("l");
boolean isR = str.contains("r");

if (isR ^ isL) {
if (isR) {
i.remove();
}
else {
temp.add(str);
temp.add(str);
}
}
else {
temp.add(str);
}
}
return temp;
}

关于java - 需要从 arraylist 中删除其中包含字母的字符串,如果包含其他则不要触摸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21788415/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com