Check If Word Is Valid After Substitutions LeetCode solution in Java

1
class Solution {
2
public boolean isValid(String s) {
3

4
// Lets see how we can solve that as we know we have only abc in string.
5
// Like aabcbc
6
// See as that ((b)b) Think a is '(' and c is ')'.
7
// If a string is made by using abc only we can remove abc to make it empty also.
8

9
// Think in Reverse Way.
10

11
Stack<Character> stack = new Stack<>();
12
char[] arr = s.toCharArray();
13
for (int i = 0; i < arr.length; i++) {
14

15
// We have to work only when we get ')' means c.
16

17
if (arr[i] == 'c') {
18
// If we at c means we have 2 elements before us a and b.
19
// When we first pop we get b at second pop we get a
20

21
// If this all hold true we will delete a and b we are not adding c so c also
22

23
if (stack.size() >= 2 && stack.pop() == 'b' && stack.pop() == 'a') {
24

25
} else {
26

27
// If anywhere we get false in any condition that means this is not a
28
// valid set i.e. abc pattern is not present.
29

30
return false;
31
}
32
} else {
33
// For a and b we simply add.
34

35
stack.push(arr[i]);
36
}
37
}
38

39
// If we have only abc pattern the stack will become empty.
40

41
return stack.size() == 0;
42
}
43
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0