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

301. Remove Invalid Parentheses

时间:2016-09-24 07:03:55      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:

Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results.

Note: The input string may contain letters other than the parentheses ( and ).

Examples:

"()())()" -> ["()()()", "(())()"]
"(a)())()" -> ["(a)()()", "(a())()"]
")(" -> [""]

这题好麻烦。。。基本参考了discussion解法。ref:https://discuss.leetcode.com/topic/28827/share-my-java-bfs-solution
整体思路:bfs,每一层都尝试删除一个符号。如果valid就输出并且从这一层跳出。因此用一个found的boolean来判断这层是不是已经有了。如果没有这个boolean会一直搜索到以下层,
然而题目要求是min,所以没有必要。用一个set来存要检查的避免重复,类似月(()),删除重复的检查没有必要。还要构建一个isvalid辅助method来解决。
总之好麻烦。。。。理解思路即可吧。
public class Solution {
    public List<String> removeInvalidParentheses(String s) {
        List<String> res=new ArrayList<String>();
        if(s==null)
        {
            return res;
        }
        Queue<String> check=new LinkedList<>();
        Set<String> check2=new HashSet<String>();
        check.offer(s);
        check2.add(s);
        boolean found=false;
        while(!check.isEmpty())
        {
            s=check.poll();
            if(isValid(s))
            {
                res.add(s);
                found=true;
            }
            if(found)
            {
                continue;
            }
            for(int i=0;i<s.length();i++)
            {
                char pa=s.charAt(i);
                if(pa==‘(‘||pa==‘)‘)
                {
            String another=s.substring(0,i)+s.substring(i+1);
            if(!check2.contains(another))
            {
                check.offer(another);
                check2.add(another);
            }
                }
            }
        }
        return res;
        
    }
    public boolean isValid(String s)
    {
        int count=0;
        for(int i=0;i<s.length();i++)
        {
            if(s.charAt(i)==‘(‘)
            {
                count++;
            }
            if(s.charAt(i)==‘)‘)
            {
                count--;
            }
            if(count<0)
            {
                return false;
            }
        }
        if(count==0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

 

301. Remove Invalid Parentheses

标签:

原文地址:http://www.cnblogs.com/Machelsky/p/5902307.html

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