前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LWC 50:678. Valid Parenthesis String

LWC 50:678. Valid Parenthesis String

作者头像
用户1147447
发布2019-05-26 00:44:49
3110
发布2019-05-26 00:44:49
举报
文章被收录于专栏:机器学习入门

LWC 50:678. Valid Parenthesis String

Problem:

Given a string containing only three types of characters: ‘(‘, ‘)’ and ‘*’, write a function to check whether this string is valid. We define the validity of a string by these rules:

  • Any left parenthesis ‘(’ must have a corresponding right parenthesis ‘)’.
  • Any right parenthesis ‘)’ must have a corresponding left parenthesis ‘(‘.
  • Left parenthesis ‘(’ must go before the corresponding right parenthesis ‘)’.
  • ‘*’ could be treated as a single right parenthesis ‘)’ or a single left parenthesis ‘(’ or an empty string.
  • An empty string is also valid.

Example 1:

Input: “()” Output: True

Example 2:

Input: “(*)” Output: True

Example 3:

Input: “(*))” Output: True

Note:

  • The string size will be in the range [1, 100]. Discuss

思路: 采用暴力搜索,真正需要遍历的状态是”*”,每次遇到星,都有三种状态:1. 不做任何操作,2. 左括号+1, 3. 右括号+1,合法状态为左括号始终大于等于右括号,且最终输出left == right。

代码如下:

代码语言:javascript
复制
    public boolean checkValidString(String s) {
        return robot(s.toCharArray(), 0, 0, 0);
    }

    boolean robot(char[] cs, int i, int left, int right) {
        if (i >= cs.length) {
            return left == right;
        }
        for (int j = i; j < cs.length; ++j) {
            if (cs[j] == '(')
                left++;
            else if (cs[j] == ')') {
                right++;
                if (right > left) return false;
            } 
            else {
                return robot(cs, j + 1, left, right) || robot(cs, j + 1, left + 1, right)
                        || robot(cs, j + 1, left, right + 1);
            }
        }
        return left == right;
    }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017年09月21日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • LWC 50:678. Valid Parenthesis String
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档