我正在尝试编写一个递归方法,在字符arraylist中的字符之间添加星号。我也试图避免在该方法中进行硬编码。这是我尝试使用测试代码和所需的输出。我正在尝试使用列表迭代器,但我想知道是否有更好的方法?
public static String addStars(List<Character> str) {
if (str.isEmpty()) {
return "";
}
else {
char hold = '*';
str.listIterator(1).add(hold);
str.listIterator(3).add(hold);
}
return str.get(0) + addStars(str.subList(2, str.size()));
}
public static void main(String[] args) {
ArrayList<Character> example = new ArrayList<>(Arrays.asList('a', 'b', 'c'));
System.out.println(example); // [a, b, c]
System.out.println(addStars(example)); // a*b*c
System.out.println(example); // [a, *, b, *, c]
}
}
答案 0 :(得分:1)
这应该这样做。
public class Whatever {
private final static char hold = '*';
public static String addStars(List<Character> str) {
if (str.isEmpty()) {
return "";
} else if (str.size() < 2) {
//Don't add star after last character
return "" + str.get(0);
}
//Add only one star per iteration
str.listIterator(1).add(hold);
List<Character> sublist = str.subList(2, str.size());
return "" + str.get(0) + hold + addStars(sublist);
}
public static void main(String[] args) {
ArrayList<Character> example = new ArrayList<>(Arrays.asList('a', 'b', 'c'));
System.out.println(example); // [a, b, c]
System.out.println(addStars(example)); // a*b*c
System.out.println(example); // [a, *, b, *, c]
}
}
答案 1 :(得分:0)
这应该做到
public static void addStars(int offset, List<Character> str) {
if (offset < str.size()) {
str.add(offset, '*');
addStars(offset + 2, str);
}
}
public static void main(String[] args) {
ArrayList<Character> example = new ArrayList<>(Arrays.asList('a', 'b', 'c'));
System.out.println(example); // [a, b, c]
addStars(1, example);
System.out.println(example); // [a, *, b, *, c]
}
}
答案 2 :(得分:0)
public static void addStars() {
ArrayList<Character> example = new ArrayList<>(Arrays.asList('a', 'b', 'c'));
List<Character> modList = new ArrayList<Character>();
//There is where the magic happens.
char CHAR_TO_ADD = '*';
//Interating over the characters
for (char temp : example) {
modList.add(CHAR_TO_ADD);
modList.add(temp);
}
for (char temp : modList) {
System.out.print(temp + " ");
}
}
我认为你正在寻找这样的东西。 我已经为每个松散包含了一个因为它们在处理列表时更容易。如果你想在最后修剪最后一个字符,那么你就可以在每个字符前面加上一个星号。如果你需要做的就是交换staredList.add(temp)和staredList.add(CHAR_TO_ADD)。
另一种选择可能是使用for循环,这样你就可以更好地控制你正在查看和管理的列表的位置。
答案 3 :(得分:0)
你坚持递归吗?问题是您正在更改原始列表,并且最后一行addStars(str.subList(2, str.size()))
每次都从更长的列表创建子列表,因此您的递归永远不会结束。如果你想要遵循这种方法,你应该每次引入一些索引和增量。