码迷,mamicode.com
首页 > 其他好文 > 详细

[lintcode easy]Valid Parentheses

时间:2015-12-01 07:12:30      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:

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;
    }
}

 

[lintcode easy]Valid Parentheses

标签:

原文地址:http://www.cnblogs.com/kittyamin/p/5009007.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!