
1003. Check If Word Is Valid After Substitutions
发布日期:2021-05-09 02:51:27
浏览次数:20
分类:博客文章
本文共 1585 字,大约阅读时间需要 5 分钟。
We are given that the string
"abc"
is valid.From any valid string
V
, we may splitV
into two piecesX
andY
such thatX + Y
(X
concatenated withY
) is equal toV
. (X
orY
may be empty.) Then,X + "abc" + Y
is also valid.If for example
S = "abc"
, then examples of valid strings are:"abc", "aabcbc", "abcabc", "abcabcababcc"
. Examples of invalid strings are:"abccba"
,"ab"
,"cababc"
,"bac"
.Return
true
if and only if the given stringS
is valid.
Example 1:
Input: "aabcbc"Output: trueExplanation: We start with the valid string "abc".Then we can insert another "abc" between "a" and "bc", resulting in "a" + "abc" + "bc" which is "aabcbc".Example 2:
Input: "abcabcababcc"Output: trueExplanation: "abcabcabc" is valid after consecutive insertings of "abc".Then we can insert "abc" before the last letter, resulting in "abcabcab" + "abc" + "c" which is "abcabcababcc".Example 3:
Input: "abccba"Output: falseExample 4:
Input: "cababc"Output: false
Note:
1 <= S.length <= 20000
S[i]
is'a'
,'b'
, or'c.
Approach #1: Stack. [Java]
class Solution { public boolean isValid(String S) { Stackstack = new Stack<>(); for (int i = 0; i < S.length(); ++i) { if (S.charAt(i) == 'c') { if (stack.empty() || stack.pop() != 'b') return false; if (stack.empty() || stack.pop() != 'a') return false; } else stack.push(S.charAt(i)); } return stack.empty(); }}
������
Analysis:
Keep a stack, whenever meet character of 'c', pop 'b' and 'a' at the end of the stack. Otherwise, return false;
Reference:
发表评论
最新留言
第一次来,支持一个
[***.219.124.196]2025年05月01日 14时52分28秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
numpy版本问题
2021-05-14
无法打开文件“opencv_world330d.lib”的解决办法
2021-05-14
maven项目通过Eclipse上传到svn上面,再导入到本地出现指定的类找不到的问题
2021-05-14
maven 项目部署到tomcat下 没有class文件
2021-05-14
算法训练 未名湖边的烦恼(递归,递推)
2021-05-14
算法训练 完数(循环,数学知识)
2021-05-14
什么是接口
2021-05-14
2020版nodejs12.18.3安装配置教程
2021-05-14
iview组件库中,Form组件里的Input,无法正确绑定on-enter事件
2021-05-14
记录-基于springboot+vue.js实现的超大文件分片极速上传及流式下载
2021-05-14
JavaScript高级程序设计第四版学习记录-第九章代理与反射
2021-05-14
怎么解决Windows 10文件/文件夹正在使用无法删除
2021-05-14
matlab函数:fix 向0取整
2021-05-14
ORCAD创建元件库时,格点对不起怎么办
2021-05-14
Allegro中如何消除器件本身Pin间距报错
2021-05-14
AD中拖动器件,无法移动在一起如何解决
2021-05-14
linux--练习001-基础类型
2021-05-14
Flask--简介
2021-05-14