Wednesday, April 13, 2022

Leet Code 838. Push Dominoes

https://leetcode.com/problems/push-dominoes/


Example 1:

Input: dominoes = "RR.L"
Output: "RR.L"
Explanation: The first domino expends no additional force on the second domino.







package pep.Day62;

import java.util.LinkedList;
import java.util.Queue;

public class LeetCode_838_Push_dominoes {
public static void main(String[] args) {
System.out.print(pushDominoes(".L.R...LR..L.."));
}

public static String pushDominoes(String dominoes) {
Queue<Pair> que = new LinkedList<>();
char[] str = dominoes.toCharArray();

// yha pr humne pairs bnakr queue me add kr diya
for (int i = 0; i < str.length; i++) {
char c = str[i];
if (c != '.')
que.add(new Pair(c, i));
}

while (!que.isEmpty()) {
Pair remove = que.remove();
if (remove.status == 'L') {
// condition: index min. 1 hona cheye, tabhi 0th index ka check ho paega
if (remove.index > 0 && str[remove.index - 1] == '.') {
str[remove.index - 1] = 'L';
que.add(new Pair('L', remove.index - 1));
}
} else {
// condition: agr jo remove kiya hai uska index +1 chota hona chye mere array se
// aur uski right me next position pr dot hona cheye
// toh yeh mera potential right bnn skta hai
if (remove.index + 1 < str.length && str[remove.index + 1] == '.') {
// agr right ki next of next me Left wala exist krta hai
// to left wale ko bhi remove kr denge
if (remove.index + 2 < str.length && str[remove.index + 2] == 'L') {
que.remove();
} else {
str[remove.index+1] = 'R';
que.add(new Pair('R', remove.index + 1));
}
}

}
}

return new String(str);

}

static class Pair {
char status;
int index;

Pair(char status, int index) {
this.status = status;
this.index = index;
}
}
}









No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...