How to make it check the all index ?
package com.codegym.task.task07.task0716;
import java.util.ArrayList;
/*
R or L
*/
public class Solution {
public static void main(String[] args) throws Exception {
ArrayList<String> list = new ArrayList<String>();
list.add("rose"); // 0
list.add("love"); // 1
list.add("lyre"); // 2
list = fix(list);
for (String s : list) {
System.out.println(s);
}
}
public static ArrayList<String> fix(ArrayList<String> list) {
for (int i = 0; i < list.size(); i++)
{
list.get(i);
if (list.get(i).contains("r") && !list.get(i).contains("l"))
{
list.remove(i);
}
else if (list.get(i).contains("l") && !list.get(i).contains("r"))
{
list.add(list.get(i));
}
else if (list.get(i).contains("r") && list.get(i).contains("l"))
{
continue;
}
}
return list;
}
}
Canot get it
Under discussion
Comments (2)
- Popular
- New
- Old
You must be signed in to leave a comment
ira.iurciuc
14 February 2019, 12:45
My solution:
- create a new ArrayList in the fix() method
- if the element of list contains "r" and does not contain "l" remove it and then decrement i
- if the element of list contains "l" and does not contain "r" send it to the new ArrayList twice, (send the original and the duplicate)
- if the element of list does not contain "r" either "l", send the element to the new ArrayList without doing anything with it
+2
Syed Tayyab ul Mazhar
28 January 2019, 07:44
Removing causes the list size to decrease by 1, this causes the elements to shift back, because of which an element that had index 2, will have index 1 after an element from index 1 is removed, and because index 1 has already been checked, it won't be checked again. So among other things, you need to decrease i by 1 after removing an element.
There is something else that you need to do, besides decrementing i, which I'll leave to you.
0