[lintcode easy]Valid Parentheses

Valid Parentheses

 

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

Example

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

 

Java的String中的subString()方法

方法如下:
public String substring(int beginIndex, int endIndex)
第一个int为开始的索引,对应String数字中的开始位置,
第二个是截止的索引位置,对应String中的结束位置
1、取得的字符串长度为:endIndex - beginIndex;
2、从beginIndex开始取,到endIndex结束,从0开始数,其中不包括endIndex位置的字符
如:
"hamburger".substring(4, 8) returns "urge"
 "smiles".substring(1, 5) returns "mile"
 
 

 

public class Solution {
    /**
     * @param s A string
     * @return whether the string is a valid parentheses
     */
    public boolean isValidParentheses(String s) {
        if(s==null) return false;
        if(s.length()%2 !=0) return false;
        // Write your code here
        char[] c=s.toCharArray();
        
     
        for(int i=1;i<s.length();i++)
        {
            boolean r1= c[i-1]=='(' && c[i]==')';
            boolean r2= c[i-1]=='{' && c[i]=='}';
            boolean r3= c[i-1]=='[' && c[i]==']';
            if(r1||r2||r3)
            {
                String s1=s.substring(0,i-1)+s.substring(i+1);
                if(s1.length()==0) return true;
                else return isValidParentheses(s1);
            }
        }
        return false;
    }
}

 

转载于:https://www.cnblogs.com/kittyamin/p/5009007.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值