LC.P1003[检查替换后的词是否有效]

方法一:栈

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public boolean isValid(String s) {
int n = s.length();
if (n % 3 != 0) return false;
StringBuilder stack = new StringBuilder();
for (char c : s.toCharArray()) {
stack.append(c);
if (stack.length() >= 3 && "abc".equals(stack.substring(stack.length() - 3))) {
stack.delete(stack.length() - 3, stack.length());
}
}
return stack.isEmpty();
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$