-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path1003.java
More file actions
57 lines (57 loc) · 1.77 KB
/
Copy path1003.java
File metadata and controls
57 lines (57 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// 1003. Check If Word Is Valid After Substitutions
// Given a string s, determine if it is valid.
//
// A string s is valid if, starting with an empty string t = "", you can transform t into s after performing the following operation any number of times:
//
// Insert string "abc" into any position in t. More formally, t becomes tleft + "abc" + tright, where t == tleft + tright. Note that tleft and tright may be empty.
// Return true if s is a valid string, otherwise, return false.
//
//
//
// Example 1:
//
// Input: s = "aabcbc"
// Output: true
// Explanation:
// "" -> "abc" -> "aabcbc"
// Thus, "aabcbc" is valid.
// Example 2:
//
// Input: s = "abcabcababcc"
// Output: true
// Explanation:
// "" -> "abc" -> "abcabc" -> "abcabcabc" -> "abcabcababcc"
// Thus, "abcabcababcc" is valid.
// Example 3:
//
// Input: s = "abccba"
// Output: false
// Explanation: It is impossible to get "abccba" using the operation.
// Example 4:
//
// Input: s = "cababc"
// Output: false
// Explanation: It is impossible to get "cababc" using the operation.
//
//
// Constraints:
//
// 1 <= s.length <= 2 * 104
// s consists of letters 'a', 'b', and 'c'
//
// Runtime: 7 ms, faster than 80.48% of Java online submissions for Check If Word Is Valid After Substitutions.
// Memory Usage: 39.2 MB, less than 72.53% of Java online submissions for Check If Word Is Valid After Substitutions.
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (char c: s.toCharArray()) {
if (c == 'c') {
if (stack.isEmpty() || stack.pop() != 'b') return false;
if (stack.isEmpty() || stack.pop() != 'a') return false;
} else {
stack.push(c);
}
}
return stack.isEmpty();
}
}