http://community.topcoder.com/stat?c=problem_statement&pm=13243

就是能否通过把字符串中的'X'替换成"()", "[]", and "{}"来变成合法的括号字符串,

"([]X()[()]XX}[])X{{}}]"
Returns: "possible"
You can replace 'X's respectively with '{', '(', ')' and '['.

DFS搜索,Valid的判断使用stack。

#include <stack>
#include <vector>
#include <string>
using namespace std; class BracketExpressions {
public:
string candidates; string ifPossible(string expression)
{
candidates = "()[]{}";
vector<int> xPos;
for (int i = 0; i < expression.length(); i++)
{
if (expression[i] == 'X')
{
xPos.push_back(i);
}
}
bool possible = ifPossRe(expression, 0, xPos);
if (possible)
return "possible";
else
return "impossible";
} bool isValid(const string &expression)
{
stack<char> stk;
for (int i = 0; i < expression.length(); i++)
{
if (stk.empty())
{
stk.push(expression[i]);
}
else if (match(stk.top(), expression[i]))
{
stk.pop();
}
else
{
stk.push(expression[i]);
}
}
return stk.empty();
} bool match(char a, char b)
{
if (a == '(' && b == ')') return true;
if (b == '(' && a == ')') return true;
if (a == '[' && b == ']') return true;
if (b == '[' && a == ']') return true;
if (a == '{' && b == '}') return true;
if (b == '{' && a == '}') return true;
return false;
} bool ifPossRe(string &expression, int idx, vector<int> &xPos)
{
if (idx == xPos.size())
{
return isValid(expression);
}
int n = xPos[idx];
for (int i = 0; i < candidates.length(); i++)
{
char ch = expression[n];
expression[n] = candidates[i];
bool res = ifPossRe(expression, idx+1, xPos);
expression[n] = ch;
if (res)
return true;
}
return false;
}
};

http://apps.topcoder.com/wiki/display/tc/SRM+628

但其实判断Backet合法的代码是错的,因为没有判断先有左括号再有右括号,以下做法更好更简洁。

bool correctBracket(string exp)
{
stack<char> s;
// an assoicaitive array: opos[ ')' ] returns '(', opos[ ']' ] is '[', ...
map<char,char> opos = {
{ ')', '(' },
{ ']', '[' },
{ '}', '{' },
};
for (char ch: exp) {
// we push opening brackets to the stack
if (ch == '(' || ch == '[' || ch == '{' ) {
s.push(ch);
} else {
// If we find a closing bracket, we make sure it matches the
// opening bracket in the top of the stack
if (s.size() == 0 || s.top() != opos[ch]) {
return false;
} else {
// then we remove it
s.pop();
}
}
}
// stack must be empty.
return s.empty();
}

解法中还是用了基于6的幂来计算所有组合,比DFS要快。

string ifPossible(string expression)
{
vector<int> x;
int n = expression.size();
for (int i = 0; i < n; i++) {
if (expression[i] == 'X') {
x.push_back(i);
}
}
int t = x.size(); // to easily convert to base 6 we precalculate the powers of 6:
int p6[6];
p6[0] = 1;
for (int i = 1; i < 6; i++) {
p6[i] = 6 * p6[i - 1];
} const char* CHARS = "([{)]}";
for (int m = 0; m < p6[t]; m++) {
string nexp = expression;
for (int i = 0; i < t; i++) {
// (m / p6[i]) % 6 extracts the i-th digit of m in base 6.
nexp[ x[i] ] = CHARS[ (m / p6[i]) % 6 ];
}
if (correctBracket(nexp)) {
return "possible";
}
} return "impossible";
}

  

*[topcoder]BracketExpressions的更多相关文章

  1. topcoder SRM 628 DIV2 BracketExpressions

    先用dfs搜索所有的情况,然后判断每种情况是不是括号匹配 #include <vector> #include <string> #include <list> # ...

  2. TopCoder kawigiEdit插件配置

    kawigiEdit插件可以提高 TopCoder编译,提交效率,可以管理保存每次SRM的代码. kawigiEdit下载地址:http://code.google.com/p/kawigiedit/ ...

  3. 记第一次TopCoder, 练习SRM 583 div2 250

    今天第一次做topcoder,没有比赛,所以找的最新一期的SRM练习,做了第一道题. 题目大意是说 给一个数字字符串,任意交换两位,使数字变为最小,不能有前导0. 看到题目以后,先想到的找规律,发现要 ...

  4. TopCoder比赛总结表

    TopCoder                        250                              500                                 ...

  5. Topcoder几例C++字符串应用

    本文写于9月初,是利用Topcoder准备应聘时的机试环节临时补习的C++的一部分内容.签约之后,没有再进行练习,此文暂告一段落. 换句话说,就是本文太监了,一直做草稿看着别扭,删掉又觉得可惜,索性发 ...

  6. TopCoder

    在TopCoder下载好luncher,网址:https://www.topcoder.com/community/competitive%20programming/ 选择launch web ar ...

  7. TopCoder SRM 596 DIV 1 250

    body { font-family: Monospaced; font-size: 12pt } pre { font-family: Monospaced; font-size: 12pt } P ...

  8. 求拓扑排序的数量,例题 topcoder srm 654 div2 500

    周赛时遇到的一道比较有意思的题目: Problem Statement      There are N rooms in Maki's new house. The rooms are number ...

  9. TopCoder SRM 590

     第一次做TC,不太习惯,各种调试,只做了一题...... Problem Statement     Fox Ciel is going to play Gomoku with her friend ...

随机推荐

  1. 使用MongoDB的开源项目

    根据谷歌的搜索结果筛选出来的. 统计应用 counlty https://count.ly/ mongopress 开源CMS系统 http://www.mongopress.org/ Rubedo ...

  2. 用PHP判断客户端是否是手机

    <?php function isMobile(){ $useragent = isset($_SERVER['HTTP_USER_AGENT'])? $_SERVER['HTTP_USER_A ...

  3. NavigationBar的简单设置

    http://blog.csdn.net/hufeng825/article/details/7643532#) .Label属性设置 titleLabel = [[UILabel alloc] in ...

  4. Azure IaaS for IT Pros Online Event 总结

    微软一个为期4天的一个有关于Azure的介绍,主要总结了些Azure现有的技术以及将会推出东西 主题链接 http://channel9.msdn.com/Events/Microsoft-Azure ...

  5. [转]教大家如何打造使用Tcpview(tcp查看器

    原文地址:教大家如何打造使用Tcpview(tcp查看器)作者:jybasenet3   一玩 VS 对战平台的同学有一次发现了一个可以踢人的方法,就是用 TcpView 把那个连 接关掉.后来VS ...

  6. jQuery将字符串转换成json

    _menus = eval('(' + json.data + ')'); _menus = parseJSON('(' + json.data + ')');

  7. UIViewController没有随着设备一起旋转的原因

    对于iPhone app,UIViewController类提供了基本的视图管理模式.当设备改变方向的时候view controller的视图会自动随之旋转的.如果视图和子视图的autoresizin ...

  8. php配置步奏

    web运行大致流程 浏览器输入地址,回车(发送请求) 根据规则找到对应web服务器.规则如下: 首先在本机hosts文件中找对应IP 如果hosts中没有找到,则到互联网上找对应IP 如果还 ...

  9. iOS性能调优之Analyze静态分析

    之前遇到一个同事写的 陈年老工程,需要尽快的时间修改里面的东西,急用,让我帮忙.那就帮着看看. 而Analyze这个工具 真是好用. 工程存在严重的内存泄漏.  如果不解决  很容易就会出现崩溃等现象 ...

  10. iOS 计算 日期 距离 当前 系统的日期 相差 多少

    #pragma mark - 时间计算函数 - (NSTimeInterval)intervalSinceNow:(NSString *) theDate { NSDateFormatter * da ...