合法的括号序列的定义:
1.空字符为合法括号序列
2.(+合法括号序列+) 为合法括号序列
3.()+合法括号序列为合法括号序列
2.(+合法括号序列+) 为合法括号序列
3.()+合法括号序列为合法括号序列
如果能构造出来则返回恢复后任意合法的括号序列,否则返回Impossible
"()?)"
"()()"
把?替换为(即可
给定brackets字符串
(()?()变为
(())()我就想知道,设 Γ 为合法括号序列(字符串)组成的集合,x 为任一合法括号序列(字符串),按
"" ∈ Γ x ∈ Γ ⇒ "(" + x + ")" ∈ Γ x ∈ Γ ⇒ "()" + x ∈ Γ这三条规则,怎么得出
"(())()" ∈ Γ???
合法的括号序列的定义:1.空字符为合法括号序列
2.(+合法括号序列+) 为合法括号序列
3.()+合法括号序列为合法括号序列
class Solution { public: /** * * @param brackets string字符串 brackets * @return string字符串 */ string MissingBrackets(string brackets) { // write code here if(brackets.size() & 1) return "Impossible"; int nLeftBracket = 0; for(char c : brackets){ if(c == '(') nLeftBracket++; } if(nLeftBracket > (brackets.size() >> 1)) return "Impossible"; for(int i = 0; i < brackets.size(); ++i){ if(brackets[i] == '?'){ if(nLeftBracket < brackets.size() / 2){ brackets[i] = '('; nLeftBracket++; } else brackets[i] = ')'; } } stack<char> s; bool flag = true; for(char c : brackets){ if(c == '(') s.push(c); else if(s.empty()){ flag = false; break; } else s.pop(); } return (flag == true)? brackets : "Impossible"; } };
class Solution: def MissingBrackets(self , brackets): if brackets is None: return brackets brackets = list(brackets) if len(brackets)%2==1: return "Impossible" countLeft = 0 for i in range(len(brackets)): if brackets[i] == '(': countLeft+=1 if countLeft > len(brackets)/2: return "Impossible" insertLeft = len(brackets)/2-countLeft for i in range(len(brackets)): if brackets[i] == '?' and insertLeft: brackets[i] = '(' insertLeft-=1 elif brackets[i] == '?': brackets[i] = ')' count = 0 for s in range(len(brackets)): if brackets[s] == '(': count+=1 else: count-=1 if count<0: return "Impossible" return ''.join(brackets)python中的str不允许直接修改其值,所以要转换为list,最后的返回结果也要用''.join()
class Solution { public: /** * * @param brackets string字符串 brackets * @return string字符串 */ string MissingBrackets(string b) { // write code here int lcnt=0, len=b.size(); for(auto c:b) lcnt+=(c=='('); if(len%2 || lcnt>len/2) return "Impossible"; lcnt=len/2-lcnt; for(auto& c:b){ if(c=='?'){ if(lcnt) {c='(';lcnt--;} else c=')'; } } lcnt=0; for(auto c:b){ if(c=='(') lcnt++; else{ lcnt--; if(lcnt<0) return "Impossible"; } } return b; } };