您的位置:首页 > 其它

Remove Invalid Parentheses--Nice

2015-11-19 14:32 162 查看

参考链接

题目描述

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())()”]

“)(” -> [“”]

题目解答

解题思路

广度优先遍历的思想

代码实现

public class Solution {
/**
*类似广度优先遍历的思想
*/
public List<String> removeInvalidParentheses(String s){

List<String> ret = new ArrayList<>();
if(s == null)
return ret;
if(s.length() == 0){
ret.add(s);
return ret;
}

HashSet<String> visited = new HashSet<>();
ArrayDeque<String> queue = new ArrayDeque<>();
queue.add(s);
visited.add(s);
//找到了最小的就不同接下去了
boolean founded = false;
while(!queue.isEmpty()){
String temp = queue.poll();
if(isValid(temp)){
ret.add(temp);
founded = true;
}

//返回最小次数
if(founded)
continue;
//遍历所有状态
for(int i = 0; i < temp.length(); i++){
if(temp.charAt(i) != ')' && temp.charAt(i) != '(')
continue;
String splitStr = temp.substring(0, i) + temp.substring(i+1);
if(!visited.contains(splitStr)){
visited.add(splitStr);
queue.add(splitStr);
}
}
}
return ret;
}

/**
* 判断字符串的格式是否有效
* 方法非常巧妙
* 通过count来记录
*/
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-- == 0)
return false;
}

return count == 0;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: