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

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

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.  (Xor 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: 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: false

Example 4:

Input: "cababc"Output: false

 

Note:

  1. 1 <= S.length <= 20000
  2. S[i] is 'a''b', or 'c.

 

Approach #1: Stack. [Java]

class Solution {    public boolean isValid(String S) {        Stack
stack = 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:

 

转载于:https://www.cnblogs.com/ruruozhenhao/p/10799417.html

你可能感兴趣的文章
uva 111 History Grading(lcs)
查看>>
Python学习week2-python介绍与pyenv安装
查看>>
php判断网页是否gzip压缩
查看>>
一个有意思的js实例,你会吗??[原创]
查看>>
sql server中bit字段实现取反操作
查看>>
Part3_lesson2---ARM指令分类学习
查看>>
jQuery拖拽原理实例
查看>>
JavaScript 技巧与高级特性
查看>>
Uva 11729 Commando War
查看>>
增强学习(一) ----- 基本概念
查看>>
ubuntu下USB连接Android手机
查看>>
C# 语句 分支语句 switch----case----.
查看>>
反射获取 obj类 的属性 与对应值
查看>>
表单中的readonly与disable的区别(zhuan)
查看>>
win10下安装配置mysql-8.0.13--实战可用
查看>>
周记2018.8.27~9.2
查看>>
MySQL中 1305-FUNCTION liangshanhero2.getdate does not exit 问题解决
查看>>
python序列化和json
查看>>
mongodb
查看>>
SSH-struts2的异常处理
查看>>