国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

301. Remove Invalid Parentheses

2019-11-08 03:23:01
字體:
來源:轉載
供稿:網友

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


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 内黄县| 安泽县| 开平市| 高阳县| 策勒县| 临颍县| 银川市| 松滋市| 郴州市| 色达县| 宁蒗| 河东区| 班戈县| 克什克腾旗| 中超| 连云港市| 万年县| 南部县| 玉门市| 黑水县| 衡东县| 南昌市| 集安市| 哈尔滨市| 海宁市| 青海省| 盐边县| 宣恩县| 雷波县| 泾阳县| 河北区| 景德镇市| 通城县| 思茅市| 奎屯市| 台南市| 吉安县| 边坝县| 镇巴县| 班玛县| 承德县|