[英]Repeating sequences in an array
In this problem, I am to write a method that accepts an ArrayList
of strings
and an integer
. 在这个问题中,我要编写一个接受
strings
和integer
的ArrayList
的方法。 In this case, the integer would repeat the individual word a number of times as indicated by the integer. 在这种情况下,整数将重复单个单词多次,如整数所示。 For example, if the list stores the values
["how", "are", "you?"]
before the method is called and k is 4, it should store the values ["how", "how", "how", "how", "are", "are", "are", "are", "you?", "you?", "you?", "you?"]
If k is 0 or negative, the list should be empty after the call. 例如,如果列表在调用方法之前存储值
["how", "are", "you?"]
,且k为4,则应存储值["how", "how", "how", "how", "are", "are", "are", "are", "you?", "you?", "you?", "you?"]
如果k为0或负数,则列表通话后应该为空。
public static void stutter(ArrayList<String> thing, int k) {
if (k <= 0) {
thing.clear(); // if k is 0
return;
}
for (int i = 0; i< thing.size(); i+= k) {
String temp = thing.get(i);
for (int j = 0; j < k; j++) {
thing.add(temp);
}
}
}
Never mind, I solved it; 没关系,我解决了; just some rearranging and it worked.
只是进行了一些重新排列,它奏效了。
I haven't tested it please verify 我没有测试过,请确认
public static void stutter(ArrayList<String> thing, int k) {
if (k <= 0) {
thing.clear(); // if k is 0
return;
}
ArrayList<String> newList = new ArrayList<>();
for (int i = 0; i< thing.size(); i++) {
String temp = thing.get(i);
for (int j = 0; j < k; j++) {
newList.add(temp);
}
}
thing.clear();
thing.addAll(newList);
}
Never mind, I solved it; 没关系,我解决了; just some rearranging and it worked.
只是进行了一些重新排列,它奏效了。
public static void stutter(ArrayList<String> thing, int k) {
if (k <= 0) {
thing.clear();
return;
}
for (int i = 0; i< thing.size(); i+= k) {
String temp = thing.get(i);
for (int j = 1; j < k; j++) {
thing.add(i, thing.get(i));
}
if (i == thing.size()) {
return;
}
}
}
If you guys can find any holes in this, feel free to point them out. 如果你们能找到任何漏洞,请随时指出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.