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

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

题目如下:

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: 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'

解题思路:这个题目有点用巧的意思了,可以逆向思维。每次从input中删除掉一个"abc",如果最后input能变成空就是True,否则就是False。

代码如下:

class Solution(object):    def isValid(self, S):        """        :type S: str        :rtype: bool        """        while len(S) > 0:            inx =  S.find('abc')            if inx == -1:                return False            S = S[:inx] + S[inx+3:]        return True

 

转载于:https://www.cnblogs.com/seyjs/p/10469214.html

你可能感兴趣的文章
[BZOJ] 4196 [Noi2015]软件包管理器
查看>>
how to use http.Agent in node.js
查看>>
php数组分页类
查看>>
从NoSQL到NewSQL,谈交易型分布式数据库建设要点
查看>>
#HTTP协议学习# (一)request 和response 解析
查看>>
心情随笔
查看>>
ICMP:Internet控制报文协议
查看>>
Spring基础
查看>>
cvc-complex-type.2.3: Element 'beans' cannot have character [children]
查看>>
OCX开发与第三方OCX封装
查看>>
SQLite数据库中的SQL语句
查看>>
缓动框架的封装
查看>>
Min Stack
查看>>
hibernate-注解及配置
查看>>
在非PAE模式下,为啥PDE表开始于0xC0300000
查看>>
Python开发之数据类型
查看>>
zabbix3.2监控mongodb
查看>>
Code Project精彩系列(转)
查看>>
CSS3_02之2D、3D动画
查看>>
洛谷P2375 动物园
查看>>