mardi 15 juin 2021

I unable to understand

I found this but unable to understand the if condition used in this program.:if(!stack.isEmpty() && stack.peek()[0] == i)

class Solution {

public String removeDuplicates(String s, int k) {
    Stack<int[]> stack = new Stack();
    for(char i : s.toCharArray()){
        if(!stack.isEmpty() && stack.peek()[0] == i){
            stack.peek()[1]++;
        }else{
            stack.push(new int[]{i,1});
        }
        
        if(stack.peek()[1] == k){
            stack.pop();
        }
    }
    StringBuilder result = new StringBuilder();
    
    while(!stack.isEmpty()){
        int len = stack.peek()[1];
        char ch = (char)stack.pop()[0];
        while(len>0){
            result.append(ch);
            len--;
        }
    }
    
    return result.reverse().toString();
    
}

}

Aucun commentaire:

Enregistrer un commentaire