301. Remove Invalid Parentheses

来源:互联网 发布:gta5帧数优化提高帧数 编辑:程序博客网 时间:2024/06/10 00:50

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())()"]")(" -> [""]


思路:因为是要删除的最少,那就是BFS

import java.util.ArrayList;import java.util.HashSet;import java.util.LinkedList;import java.util.List;import java.util.Queue;import java.util.Set;/* * BFS solution */public class Solution {    public List<String> removeInvalidParentheses(String s) {            List<String> rst = new ArrayList<String>();        Set<String> visited = new HashSet<String>();    Queue<String> queue = new LinkedList<String>();    Queue<String> queue2 = new LinkedList<String>();        queue.add(s);    visited.add(s);        boolean found = false;    while(!queue.isEmpty()) {    String ss = queue.remove();        if(isValid(ss)) {    rst.add(ss);    found = true;    }        if(!found) {    for(int i=0; i<ss.length(); i++) {    String t = ss.substring(0, i) + ss.substring(i+1);    if(!visited.contains(t)) {    queue2.add(t);    visited.add(t);    }    }    }        if(queue.isEmpty()) {    if(found)break;    queue = queue2;    queue2 = new LinkedList<String>();    }        }        return rst;    }            public boolean isValid(String s) {    char[] cs = s.toCharArray();    int cnt = 0;    for(char c : cs) {    if(c == '(')cnt++;    if(c == ')')cnt--;    if(cnt < 0)return false;    }    return cnt == 0;    }}


0 0
原创粉丝点击