博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode刷题:1003. Check If Word Is Valid After Substitutions
阅读量:4039 次
发布时间:2019-05-24

本文共 1772 字,大约阅读时间需要 5 分钟。

LeetCode刷题:1003. Check If Word Is Valid After Substitutions

原题链接:

We are given that the string "abc" is valid.

From any valid string V, we may split V into two pieces X and Y such that X + Y (X concatenated with Y) is equal to V.  (X or Y 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 string S is valid.

 

Example 1:

Input: "aabcbc"

Output: true
Explanation: 
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: true
Explanation: 
"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: false
Example 4:

Input: "cababc"

Output: false
 

Note:

1 <= S.length <= 20000

S[i] is 'a', 'b', or 'c'


算法设计

class Solution {    public boolean isValid(String S) {        Stack
stack = new Stack<>(); for(char ch : S.toCharArray()){ switch(ch){ case 'a': case 'b': stack.push(ch); break; case 'c': if(!stack.isEmpty() && stack.peek() == 'b') stack.pop(); else return false; if(!stack.isEmpty() && stack.peek() == 'a') stack.pop(); else return false; break; } } return stack.isEmpty(); }}

程序运行结果,Accepted.

 

转载地址:http://pntdi.baihongyu.com/

你可能感兴趣的文章
Android2.1消息应用(Messaging)源码学习笔记
查看>>
Phone双模修改涉及文件列表
查看>>
android UI小知识点
查看>>
Android之TelephonyManager类的方法详解
查看>>
android raw读取超过1M文件的方法
查看>>
ubuntu下SVN服务器安装配置
查看>>
MPMoviePlayerViewController和MPMoviePlayerController的使用
查看>>
CocoaPods实践之制作篇
查看>>
[Mac]Mac 操作系统 常见技巧
查看>>
苹果Swift编程语言入门教程【中文版】
查看>>
捕鱼忍者(ninja fishing)之游戏指南+游戏攻略+游戏体验
查看>>
iphone开发基础之objective-c学习
查看>>
iphone开发之SDK研究(待续)
查看>>
计算机网络复习要点
查看>>
Variable property attributes or Modifiers in iOS
查看>>
NSNotificationCenter 用法总结
查看>>
C primer plus 基础总结(一)
查看>>
剑指offer算法题分析与整理(一)
查看>>
剑指offer算法题分析与整理(三)
查看>>
Ubuntu 13.10使用fcitx输入法
查看>>