关闭

LeetCode Remove Invalid Parenthese

标签: Leetcode
79人阅读 评论(0) 收藏 举报
分类:

LeetCode 每日刷题!!

Remove Invalid Parentheses

这道题在做的时候用到了BFS因为它要求的是最优解

层次依次为删除0个元素,1个元素,2个元素。。。

如果在一层找到符合要求的就返回

在做的时候考虑效率问题,要对BFS进行剪枝,不然会timelimit, 使用的方法一:出现过的就加入visited里面不再加入叶子节点,二:visited用hash,提高查找效率


#include <iostream>
#include <stdio.h>
#include <string>
#include <map>
#include <vector>
#include <algorithm>
#include <unordered_set>
#include <queue>
#include <stack>
#include <assert.h>
#include <set>
using namespace std;

class Solution {
public:
	vector<string> removeInvalidParentheses(string s) {
		set<string> visited;
		string *current = &s;
		vector<string> ans;
		vector<string> layerSet;
		vector<string> nextlayer;
		if (s == "")
		{
			ans.push_back("");
			return ans;
		}
		layerSet.push_back(s);

		while (layerSet.size() != 0)
		{
			//each layer of a BFT, the optimize have the least delete number
			//and each loop have the same delete num.
			for (int i = 0; i < layerSet.size(); i++)
			{
				*current = layerSet[i];
				if (isValid(*current))
				{
					ans.push_back(*current);
				}
				
			}
			if (ans.size() != 0)
			{
				return ans;
			}
			for (int i = 0; i < layerSet.size(); i++)
			{
				*current = layerSet[i];
				for (int i = 0; i < current->size(); i++)
				{
					if ((*current)[i] != '(' && (*current)[i] != ')')
					{
						continue;
					}
					string tmp = current->substr(0, i) + current->substr(i + 1);
					if (tmp == "")
					{
						ans.push_back("");
						return ans;
					}
					
					if (visited.find(tmp) == visited.end())
					{
						nextlayer.push_back(tmp);
						visited.insert(tmp);
					}

				}
			}
			layerSet.swap(nextlayer);
			
		}
		return ans;
	}

	bool isValid(string s)
	{
		int num = 0;
		if (s.size() == 0)
		{
			return false;
		}
		for (int i = 0; i < s.size(); i++)
		{
			if (s[i] == '(') {
				num++;
			}
			if (s[i] == ')') {
				num--;
			}
			if (num < 0)
				return false;
		}
		return num == 0;
	}
};

int main()
{
	string test1 = ")()m)(((()((()((((";
	vector<string> ans;
	Solution *solu = new Solution();
	ans = solu->removeInvalidParentheses(test1);
	for (int i = 0; i < ans.size(); i++)
	{
		cout << ans[i] << endl;
	}

	system("pause");
	return 0;


}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:455次
    • 积分:33
    • 等级:
    • 排名:千里之外
    • 原创:3篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档