C# 检查字符串是否有平衡圆括号
我正在阅读算法设计手册第二版,这是一个练习题。引述问题 编译器和应用程序的常见问题 文本编辑器正在确定 字符串中的括号是 平衡和适当的嵌套。对于 例如,字符串((())())() 包含正确嵌套的 括号,其中包含字符串)()( 和())不要。给出一个算法 如果字符串包含 适当嵌套和平衡 括号,否则为false。 要获得全额信用,请确定该职位 如果 该字符串没有正确嵌套,并且 平衡的 问题在堆栈、队列和列表类别下。这是我用C写的C# 检查字符串是否有平衡圆括号,c#,algorithm,C#,Algorithm,我正在阅读算法设计手册第二版,这是一个练习题。引述问题 编译器和应用程序的常见问题 文本编辑器正在确定 字符串中的括号是 平衡和适当的嵌套。对于 例如,字符串((())())() 包含正确嵌套的 括号,其中包含字符串)()( 和())不要。给出一个算法 如果字符串包含 适当嵌套和平衡 括号,否则为false。 要获得全额信用,请确定该职位 如果 该字符串没有正确嵌套,并且 平衡的 问题在堆栈、队列和列表类别下。这是我用C写的 const char left圆括号='('; 常量字符右括号=')'
const char left圆括号='(';
常量字符右括号=')';
bool arecaresbalanced(字符串str,out-int-errorAt)
{
变量项=新堆栈(str.Length);
误差=-1;
对于(int i=0;i0)
{
errorAt=items.Peek()+1;
返回false;
}
返回true;
}
这很有效。但我不确定这是解决这个问题的正确方法。欢迎任何更好的想法。我认为这是我们的意图,但实际上,如果您只处理括号,您只需要减少和增加一个计数器。如果您正在处理方括号、尖括号、大括号或任何您想要使用的字符配对,那么您将需要一个像您所做的那样的堆栈
您也可以使用列表,将head元素拉离或拉离,但实际上堆栈可能无论如何都是作为列表实现的——至少在ocaml中是这样。正如Villageidiot所说,这很好。您还可以递归地实现它,这可能更优雅,也可能不优雅。最后,您可能希望要求匹配的括号在它们之间包含有效的内容,以便允许“(a)”而不是“()”为什么返回值和out参数提供相同的信息 您可以返回一个int:-1=balanced,否则返回错误的索引
inti;
内伦;
煤焦爆裂;
斯塔克街;
string a=“({static public bool CheckForBalancedBracketing(string IncomingString)
{
/*******************************************************************
*检查支架是否平衡的最简单方法是启动*
*从左到右计数,每个开口括号加一个“(”*
*每一个右括号减去1,最后是“)”*
*总和应为零,任何时候都不应计数*
*下降到零度以下*
* *
*实现:方括号计数变量是无符号的*
*整数,我们捕获一个溢出异常。如果*
*无符号变量会变为负值。这允许我们中止*
*一开始就不平衡,而不是浪费时间检查*
*字符串中的其余字符*
* *
*最后我们要做的就是检查一下计数是否正确*
*对于“平衡”结果,等于零*
* *
*******************************************************************/
常量字符左括号='(';
常量字符右括号=')';
单位括号计数=0;
尝试
{
选中//打开溢出检查。
{
for(int Index=0;Index
检查平衡圆括号
包装检查;
导入java.util.EmptyStackException;
导入java.util.Stack;
公营班车
{
公共静态void main(字符串参数[])
{
int pu=0;
int po=0;
字符串str=“())”;
系统输出打印项次(str);
Stack st=新堆栈();
对于(inti=0;iimport java.util.Stack;
公共类CheckBalancedParenthesis{
公共静态void main(字符串参数[]){
CheckBalancedParentsis checker=新的CheckBalancedParentsis();
System.out.println(checker.checkBalancedParenthesis(“{}}{}{}{}}”);
}
公共布尔checkBalancedParenthesis(字符串模式){
堆栈=新堆栈();
对于(int i=0;i<
const char LeftParenthesis = '(';
const char RightParenthesis = ')';
bool AreParenthesesBalanced(string str, out int errorAt)
{
var items = new Stack<int>(str.Length);
errorAt = -1;
for (int i = 0; i < str.Length; i++)
{
char c = str[i];
if (c == LeftParenthesis)
items.Push(i);
else if (c == RightParenthesis)
{
if (items.Count == 0)
{
errorAt = i + 1;
return false;
}
items.Pop();
}
}
if (items.Count > 0)
{
errorAt = items.Peek() + 1;
return false;
}
return true;
}
int i;
int len;
char popped;
stack<char> st;
string a = "({<<";
len = a.length();
for(i=0;i<len;i++)
{
if(a[i] == '<' || a[i] == '(' || a[i] == '[' || a[i] == '{')
{
st.push(a[i]);
continue;
}
if(a[i] == '>' || a[i] == ')' || a[i] == ']' || a[i] == '}')
{
if(st.empty())
{
cout << "stack is empty, when popped , not balanced" << endl;
return 0;
}
else
{
popped = st.top();
st.pop();
if (!((a[i] == '>' && popped == '<') || (a[i] == ')' && popped == '(') || (a[i] == '}' && popped == '{') || (a[i] == '>' && popped == '<'))) //ok
{
cout << "not balanced on character" + std::string(1,a[i]) << endl;
return 0;
}
}
}
}
if(st.empty())
{
cout << "balanced" << endl;
}
else
{
cout << "not balanced stack not empty" << endl;
}
static public bool CheckForBalancedBracketing(string IncomingString)
{
/*******************************************************************
* The easiest way to check for balanced bracketing is to start *
* counting left to right adding one for each opening bracket, '(' *
* and subtracting 1 for every closing bracket, ')'. At the end *
* the sum total should be zero and at no time should the count *
* fall below zero. *
* *
* Implementation: The bracket counting variable is an unsigned *
* integer and we trap an overflow exception. This happens if the *
* unsigned variable ever goes negative. This allows us to abort *
* at the very first imbalance rather than wasting time checking *
* the rest of the characters in the string. *
* *
* At the end all we have to do is check to see if the count *
* is equal to zero for a "balanced" result. *
* *
*******************************************************************/
const char LeftParenthesis = '(';
const char RightParenthesis = ')';
uint BracketCount = 0;
try
{
checked // Turns on overflow checking.
{
for (int Index = 0; Index < IncomingString.Length; Index++)
{
switch (IncomingString[Index])
{
case LeftParenthesis:
BracketCount++;
continue;
case RightParenthesis:
BracketCount--;
continue;
default:
continue;
} // end of switch()
}
}
}
catch (OverflowException)
{
return false;
}
if (BracketCount == 0)
{
return true;
}
return false;
} // end of CheckForBalancedBracketing()
Checking balanced parentheses
package parancheck;
import java.util.EmptyStackException;
import java.util.Stack;
public class ParnCheck
{
public static void main(String args[])
{
int pu = 0;
int po = 0;
String str = "()())";
System.out.println(str);
Stack st = new Stack();
for(int i=0; i<str.length();i++)
{
if(str.charAt(i)=='(')
{
doPush(st, str.charAt(i));
pu++;
}
else
{
try
{
doPop(st);
}
catch(EmptyStackException e)
{
System.out.println("");
}
po++;
}
}
if(pu == po)
{
System.out.println("Correct");
}
else
{
System.out.println("Wrong");
}
}
static void doPush(Stack st,char ch)
{
st.push(ch);
}
static void doPop(Stack st)
{
char c = (char)st.pop();
}
}
import java.util.Stack;
public class CheckBalancedParenthesis {
public static void main (String args[]){
CheckBalancedParenthesis checker = new CheckBalancedParenthesis();
System.out.println(checker.checkBalancedParenthesis("{}}{}{}{}{}"));
}
public boolean checkBalancedParenthesis(String pattern){
Stack stack = new Stack();
for(int i = 0; i < pattern.length();i++){
char c = pattern.charAt(i);
if(c == '{'){
stack.push(c);
}else if (c == '}'){
if(!stack.isEmpty()){
stack.pop();
} else{
System.out.println("Error at - " + i);
return false;
}
}
}
return stack.isEmpty();
}
}
using System;
class Solution
{
public int solution(string S)
{
int x1 = 0;
int x2 = 0;
for (int i = 0; i < S.Length; i++)
{
if (S[i] == ')')
if (x1 <= 0) return 0;
else x1--;
else if (S[i] == '(')
x1++;
}
if (x1 == 0)
return 1;
else
return 0;
}
}
public static bool IsBalanced(string input)
{
int count = 0;
for (int i = 0; i < input.Length; i++)
{
if (input[i] == '(') count++;
if (input[i] == ')') count--;
if (count < 0) return false;
}
if (count == 0) return true;
return false;
}
string starters = "({[<";
string enders = ")}]>";
Stack stack = new Stack();
foreach(char c in txtValue.Text.Trim())
{
if(starters.Contains(c))
{
stack.Push(c);
}
else if (enders.Contains(c))
{
if (stack.Count > 0)
{
if (enders.IndexOf(c) == starters.IndexOf(Convert.ToChar(stack.Peek())))
{
stack.Pop();
}
else
{
lblResult.Text = "Invaluid string";
}
}
}
}
if(stack.Count == 0)
{
lblResult.Text = "Valid string";
}
else
{
lblResult.Text = "InValid string";
}
public class BalancedBrackets
{
private readonly char[] _leftBrackets = new char[] {'[', '(', '{', '<'};
private readonly char[] _rightBrackets = new char[] {']', ')', '}', '>'};
public bool IsBalanced(string input)
{
int count = 0;
foreach (var character in input.ToCharArray())
{
if (_leftBrackets.Contains(character)) count++;
if (_rightBrackets.Contains(character)) count--;
}
return count == 0;
}
}
expression.Aggregate(0, (state, ch) => state == -1 ? -1 : state + (ch == '(' ? 1 : ch == ')' ? -1 : 0)) == 0
public class Balanced {
public static boolean isbalanced(String input) {
int open = 0;
int close = 0;
for (int i=0; i< input.length();i++) {
switch (input.charAt(i)) {
case '{':
case '(':
case '[':
open++;
break;
case '}':
case ')':
case ']':
close++;
default:
break;
}
}
if (open == close){
return true;
}
else {
return false;
}
}
public static void main(String args[]) {
System.out.println(Balanced.isbalanced("()"));
}
}
bool isWellFormatted(string line)
{
Stack<char> lastOpen = new Stack<char>();
foreach (var c in line)
{
switch (c)
{
case ')':
if (lastOpen.Count == 0 || lastOpen.Pop() != '(') return false;
break;
case ']':
if (lastOpen.Count == 0 || lastOpen.Pop() != '[' ) return false;
break;
case '}':
if (lastOpen.Count == 0 || lastOpen.Pop() != '{') return false;
break;
case '(': lastOpen.Push(c); break;
case '[': lastOpen.Push(c); break;
case '{': lastOpen.Push(c); break;
}
}
if (lastOpen.Count == 0) return true;
else return false;
}
var dictionary = new Dictionary<string, string>() {
{ "{", "}" },
{"[", "]" },
{"(",")" }
};
var par = "{()}";
var queue = new Queue();
var stack = new Stack();
bool isBalanced = true;
var size = par.ToCharArray().Length;
if(size % 2 != 0)
{
isBalanced = false;
}
else
{
foreach (var c in par.ToCharArray())
{
stack.Push(c.ToString());
queue.Enqueue(c.ToString());
}
while (stack.Count > size/2 && queue.Count > size/2)
{
var a = (string)queue.Dequeue();
var b = (string)stack.Pop();
if (dictionary.ContainsKey(a) && b != dictionary[a])
{
isBalanced = false;
}
}
}
Console.WriteLine(isBalanced?"balanced!":"Not Balanced");
Console.ReadLine();
public static boolean isBalanced(String expression)
{
// pairs at the same index
List<Character> openers = Arrays.asList('{', '(', '[');
List<Character> closers = Arrays.asList('}', ')', ']');
char[] exp = expression.toCharArray();
Stack<Character> stack = new Stack<>();
for(Character character: exp){
if (openers.contains(character))
stack.push(character);
if(closers.contains(character)){
if (stack.empty())
return false;
//matching pair should be at the same index
Character opener = stack.pop();
int openerIndex = openers.indexOf(opener);
int closerIndex = closers.indexOf(character);
if (openerIndex != closerIndex)
return false;
}
}
return stack.empty();
}
-- Checks the balance of braces in a string.
-- Error case 1: More closes than open. We can identify the first culprit by index.
-- Error case 2: More opens than closes. We return the length of the String,
-- indicating that there are closed braces missing.
-- Good case: As many opens as closes. We return (True,Nothing)
checkBraces :: String -> (Bool,Maybe Int)
checkBraces [] = (True,Nothing)
checkBraces s =
let (balance,offender) = foldl account (0,-1) $ zip [0..] s in
if balance == 0
then (True,Nothing)
else (False,Just $ if -1 == offender then length s else offender)
where
account :: (Int,Int) -> (Int, Char) -> (Int,Int)
account acc@(_,off) _ | off /= -1 = acc -- Once there was an error we stop looking what happens.
account acc@(b,off) (i,'(') = (b+1,off) -- One more open brace.
account (b,off) (i,')') -- One more closed brace.
| b <= 0 = (b-1,i) -- Ouch. We closed more than we opened!
| otherwise = (b-1,off) -- Okay.
account acc (i,_) = acc -- Some other character (Not in ['(',')'])
testCases =
[ ("",True)
, ("(",False)
, (")",False)
, ("))((",False)
, ("()()",True)
, ("(()))",False)
]
test =
all ((==) True) . fmap testOne $ testCases
where
testOne (tc,expected) =
let (actual,_) = checkBraces tc in
actual == expected