C#面試題:判斷括號,是否匹配
阿新 • • 發佈:2018-12-26
例如:{[]()} {[]}{()}都是匹配的。
{[[])}是不匹配的。
主要的思路就是用棧操作,當輸入{,[,(,時入棧,輸入,),],}時出棧,最後棧為空,表示匹配,棧不為空,表示不匹配。
程式碼如下:
- bool StackDemo(string str){
- Stack stack=new Stack();//例項化棧
- for(int i=0;i<=str.Length-1;i++){//迴圈判斷,入棧
- if(str[i]=='{'||str[i]=='['||str[i]=='('){
- stack.Push(str[i]);
- }
- if(str[i]=='}'||str[i]==']'||str[i]==')){//出棧
- stack.Pop();
- }
- }
- if(stack.Count==0){//棧為空
- Console.WriteLine("匹配");
- return true;
- }else{
- foreach(Stack a in stack){//棧不為空
- Console.WriteLine("不匹配:"+a);
- return false;
- }
- }
- }
Main函式部分:
- public static void Main (string[] args)
- {
- string str="{{()}[()]}";
- StackDemo(str);
- }
大家有更好的方法,麻煩也請告訴我。