You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardexpand all lines: solution/1000-1099/1003.Check If Word Is Valid After Substitutions/README_EN.md
+49-30
Original file line number
Diff line number
Diff line change
@@ -52,6 +52,16 @@ Thus, "abcabcababcc" is valid.
52
52
53
53
## Solutions
54
54
55
+
**Solution 1: Stack**
56
+
57
+
If the string is valid, it's length must be the multiple of $3$.
58
+
59
+
We traverse the string and push every character into the stack $t$. If the size of stack $t$ is greater than or equal to $3$ and the top three elements of stack $t$ constitute the string `"abc"`, we pop the top three elements. Then we continue to traverse the next character of the string $s$.
60
+
61
+
When the traversal is over, if the stack $t$ is empty, the string $s$ is valid, return `true`, otherwise return `false`.
62
+
63
+
The time complexity is $O(n)$ and the space complexity is $O(n)$. Where $n$ is the length of the string $s$.
64
+
55
65
<!-- tabs:start -->
56
66
57
67
### **Python3**
@@ -61,13 +71,12 @@ class Solution:
61
71
defisValid(self, s: str) -> bool:
62
72
iflen(s) %3:
63
73
returnFalse
64
-
stk= []
74
+
t= []
65
75
for c in s:
66
-
if c =='c'andlen(stk) >1and stk[-2] =='a'and stk[-1] =='b':
67
-
stk = stk[:-2]
68
-
else:
69
-
stk.append(c)
70
-
returnnot stk
76
+
t.append(c)
77
+
if''.join(t[-3:]) =='abc':
78
+
t[-3:] = []
79
+
returnnot t
71
80
```
72
81
73
82
### **Java**
@@ -78,17 +87,14 @@ class Solution {
78
87
if (s.length() %3>0) {
79
88
returnfalse;
80
89
}
81
-
StringBuilderstk=newStringBuilder();
90
+
StringBuildert=newStringBuilder();
82
91
for (char c : s.toCharArray()) {
83
-
int n = stk.length();
84
-
if (c =='c'&& n >1&& stk.charAt(n -2) =='a'&& stk.charAt(n -1) =='b') {
85
-
stk.deleteCharAt(n -1);
86
-
stk.deleteCharAt(n -2);
87
-
} else {
88
-
stk.append(c);
92
+
t.append(c);
93
+
if (t.length() >=3&&"abc".equals(t.substring(t.length() -3))) {
0 commit comments