Java solution: swap with prev element in case of "D"


#1

public class Solution {
// DO NOT MODIFY THE LIST. IT IS READ ONLY
public ArrayList findPerm(final String A, int B) {
ArrayList result = new ArrayList();

    //Fill the array with -1 as placeholder
    for(int i=0; i<B; i++) {
        result.add(-1);
    }

    //Set the index 0 with value "1"
    result.set(0, 1);
    
    //Start filling from index 1
    //if c = I, min++
    //if c = D, max--, then swap with previous element
    int min = 2;
    int max = B;
    
    for(int i = 1; i < B; i++) {
        char c = A.charAt(i - 1);
        if(c == 'I') {
             result.set(i, min++);
        } else {
            result.set(i, max--);
            swap(result, i, i - 1);
        }
    }
    return result;
}

//Method to swap two elements
public void swap(ArrayList<Integer> A, int i, int j) {
    int temp = A.get(i);
    A.set(i, A.get(j));
    A.set(j, temp);
}

}