"""" 括号匹配,借助栈后进先出的性质 """ if __name__ == "__main__": s = input().strip() ans = True flag = [] for c in s: if c == '[' or c == '(': flag.append(c) elif c == ']': if not flag or flag.pop() != '[': ans = False break elif c == ')': if not flag or flag.pop() != '(': ans = False break else: pass if flag: ans = False print("true" if ans else "false")
#include <iostream> #include <string> #include <stack> using namespace std; int main(){ // 后出现,先配对: ( [ ] ) 如左图, ]要先配对,所以采用栈 string str; stack<char> st; cin >> str; for(int i = 0; i < str.length(); ++i){ if(str[i] == '(' || str[i] == '['){ st.push(str[i]); } else if(str[i] == ')'){ if(!st.empty() && st.top() == '('){ st.pop(); } else{ cout << "false" << endl; return 0; } } else if(str[i] == ']'){ if(!st.empty() && st.top() == '['){ st.pop(); } else{ cout << "false" << endl; return 0; } } } cout << "true" << endl; return 0; }
import java.util.Scanner; import java.util.Stack; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); String str = sc.nextLine(); System.out.println(check(str)); } private static boolean check(String str){ char[] chars = str.toCharArray(); Stack<Character> match = new Stack<>(); for (char ch : chars) { if (ch=='[' || ch=='('){ match.push(ch); }else if (ch==']'){ if (match.empty() || match.pop()!='[') return false; }else if (ch==')'){ if (match.empty() || match.pop()!='(') return false; } } return true; } }
s = input() left = ['[','('] right = [']',')'] pair = {'[':']','(':')'} res = [] for i in s: if i in left: res.append(i) if i in right: if res and pair[res[-1]]==i: res.pop() else: res.append(i) break print('true' if not res else 'false')
本题是很简单的一道题,当时学数据结构的书上讲到栈的部分正好就有本题的一个例子,即用栈 来保存左边括号,遇到右边括号便与当前栈顶进行匹配。但是本题在题目描述上有点粗糙,一开 始我只是输出flag,但是调试一直提示失败,然后才明白要输出的是字符串……………… #include<iostream> #include<string> #include<stack> using namespace std; int main() { string s; cin>>s; stack<char> tmp; bool flag=false; for(int i=0;i<s.size();i++) { if(s[i]=='[') tmp.push(s[i]); if(s[i]=='(') tmp.push(s[i]); if(s[i]==']') { if(tmp.empty()) { flag=false; break; } else{ char c=tmp.top(); tmp.pop(); if(c=='[') flag=true; else { flag=false; break; } } } if(s[i]==')') { if(tmp.empty()) { flag=false; break; } else{ char c=tmp.top(); tmp.pop(); if(c=='(') flag=true; else { flag=false; break; } } } } if(!tmp.empty()) flag=false; if(flag) cout<<"true"; else cout<<"false"; }
const readline = require('readline') const rl = readline.createInterface({ input: process.stdin, ouput: process.stdout }) rl.on('line', line=>{ let inArr = line.trim().split(' ') let s = inArr[0].split('') let stack = [] let flag = 1 for (let i = 0; i < s.length; i++) { if(s[i] == '[' || s[i] == '('){ stack.push(s[i]) }else if(s[i] == ']' || s[i] == ')'){ if(stack.length === 0){ flag = 0 break } let c = stack[stack.length -1] stack.pop() if((c == '[' && s[i] != ']') || ( c == '(' && s[i] != ')' )){ flag = 0 break } } } if(stack.length !== 0){ flag = 0 } console.log(flag? 'true' : 'false') })
#include<iostream> #include<stack> using namespace std; int main() { string s; cin>>s; int i=0; stack<char> t; while(i<s.size()) { if(t.empty()&&(s[i]==']'||s[i]==')')) { cout<<"false"; return 0; } else if(s[i]=='['||s[i]=='(') t.push(s[i]); else if(s[i]==']') { if(t.top()=='[') t.pop(); else { cout<<"false"; return 0; } } else if(s[i]==')') { if(t.top()=='(') t.pop(); else { cout<<"false"; return 0; } } i++; } if(t.empty()) cout<<"true"; else cout<<"false"; }
#include <bits/stdc++.h> using namespace std; int main(){ stack<char> st; bool flag=true; char c; while((c=cin.get())!='\n'){ if(c=='('||c=='[') st.push(c); else if(c==')'){ if(st.empty()||st.top()!='('){ flag=false; break; } st.pop(); } else if(c==']'){ if(st.empty()||st.top()!='['){ flag=false; break; } st.pop(); } } cout<<(flag ? "true":"false"); return 0; }
#include<stdio.h> #define MAXSIZE 1000 #define OK 1 #define ERROR 0 #define TRUE 1 #define FALSE 0 typedef struct{//顺序栈的定义 char c[MAXSIZE]; int top; }SeqStack; void initStack(SeqStack *s); int push(SeqStack *s, char c); int pop(SeqStack *s, char *c); int getTop(SeqStack *s, char *c); int isTrue(char *temp, char c); void outStack(SeqStack *s); int main() { SeqStack s, *s1 = &s; char str[MAXSIZE] = {"\0"}; scanf("%s", str); initStack(s1); for(int i = 0; str[i] != '\0'; i++) { // outStack(s1); char b, *temp = &b; char c = str[i]; switch(c) { case '(': case '[': case '{': push(s1, c);//压进栈内 break; case ')': case ']': case '}': if(getTop(s1, temp) && isTrue(temp, c)) pop(s1, temp); else { printf("false\n"); return 0; } break; } } if(s1->top != -1) { printf("false\n"); return 0; } else printf("true\n"); return 0; } //初始化顺序栈 void initStack(SeqStack *s) { s->top = -1; } //顺序进栈运算 int push(SeqStack *s, char c) { //将x置入s栈新栈顶 if(s->top == MAXSIZE - 1) return FALSE; s->top++; s->c[s->top] = c; return TRUE; } //顺序栈出栈运算 int pop(SeqStack *s, char *c) { //将栈S栈顶元素读出,放到x所指的存储空间中,栈顶指针保持不变 if(s->top < 0) return FALSE; *c = s->c[s->top]; s->top--; return TRUE; } //将栈顶元素读出 int getTop(SeqStack *s, char *a) { if(s->top < 0) return FALSE; *a = s->c[s->top]; return TRUE; } //判断括号是否匹配 int isTrue(char *temp, char c) { switch(*temp) { case '(': if(c == ')') return TRUE; else return FALSE; break; case '[': if(c == ']') return TRUE; else return FALSE; break; case '{': if(c == '}') return TRUE; else return FALSE; break; default: return FALSE; break; } }
#include <bits/stdc++.h> using namespace std; int main() { string s; cin>>s; stack<char>st; for(int i=0;i<s.size();i++) { if(s[i]=='('||s[i]=='[') st.push(s[i]); else if(s[i]==')') { if(st.top()=='(') st.pop(); else { cout<<"false"; return 0; } } else if(s[i]==']') { if(st.top()=='[') st.pop(); else { cout<<"false"; return 0; } } else continue; } if(st.empty()) cout<<"true"; else cout<<"false"; return 0; }
public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String str = in.nextLine(); Stack<Character> stack = new Stack<>(); for (int i=0;i<str.length();i++){ char c = str.charAt(i); if (c == '(' || c == '[') stack.push(c); else if (c == ')'){ if (stack.isEmpty() || stack.pop() != '(') { System.out.println(false); return; } }else if (c == ']'){ if (stack.isEmpty() || stack.pop() != '[') { System.out.println(false); return; } } } if (stack.isEmpty()) System.out.println(true); else System.out.println(false); } }
str1 = input('请输入一个字符串') left = ['(['] right = [')]'] matchingchar = {']':'[',')':'('} stack = [] flag = True for i in str1: if i in left: stack.append(i) if i in right: if stack==[]: flag= False elif matchingchar.get(i)==stack[-1]: stack.pop() else: flag == False if flag == True and stack==[]: print('True') else: print('False')
#include<iostream> (720)#include<string> #include<stack> using namespace std; int main(void){ string s; cin>>s; stack<char> st; int i; for (i = 0; i < s.size(); i++){ if (s[i] == '(' || s[i] == '[') st.push(s[i]); else if(s[i] == ']'){ if (!st.empty() && st.top() == '[') st.pop(); else{ cout<<"false"<<endl; return 0; } } else if(s[i] == ')'){ if (!st.empty() && st.top() == '(') st.pop(); else{ cout<<"false"<<endl; return 0; } } } if (st.empty()) cout<<"true"<<endl; else cout<<"false"<<endl; return 0; }
更加美丽的Java!import java.util.*; public class Main { private static final List<Character> leftBrackets = Arrays.asList('[', '('); private static final List<Character> rightBrackets = Arrays.asList(']',')'); public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (scanner.hasNextLine()){ String str = scanner.nextLine(); if (str.isEmpty()) System.out.println("false"); else System.out.println(isBalanced(str) ? "true" : "false"); } } public static boolean isBalanced(String str){ Stack<Character> stack = new Stack<>(); for (char ch : str.toCharArray()){ if (isLeftBracket(ch)) stack.push(ch); else if (isRightBracket(ch)) { if (stack.isEmpty()) return false; char top = stack.pop(); if (!match(top, ch)) return false; } } return stack.isEmpty(); } public static boolean isLeftBracket(char ch){ return leftBrackets.contains(ch); } public static boolean isRightBracket(char ch){ return rightBrackets.contains(ch); } public static boolean match(char leftBracket,char rightBracket){ return leftBrackets.indexOf(leftBracket) == rightBrackets.indexOf(rightBracket); } }
import java.util.*; public class Main{ public static void main(String[]args){ Scanner sc = new Scanner(System.in); String str = sc.nextLine(); boolean res = true; Stack stack = new Stack(); for(int k = 0;k < str.length();k++) { if(str.charAt(k) == '(' || str.charAt(k) == '[') { stack.push(str.charAt(k)); }else if(str.charAt(k) == ')') { if(stack.isEmpty() || (Character)stack.pop() != '(') { res = false; break; } }else if(str.charAt(k) == ']') { if(stack.isEmpty() || (Character)stack.pop() != '[') { res = false; break; } }else{ continue; } } if (!stack.isEmpty()) { res = false; } System.out.println(res); } }
string = input() stack = [] END = False for s in string: if s.isalpha(): continue elif s == '[' or s == '(': stack.append(s) elif s == ']': if len(stack) > 0 and stack[-1] == '[': stack.pop() else: print('false') END = True break elif s == ')': if len(stack) > 0 and stack[-1] == '(': stack.pop() else: print('false') END = True break if not END: print('true' if len(stack) == 0 else 'false')
class My_Stack: def __init__(self, elements=[]): self._elements = list(elements) def is_empty(self): #return not self._elements return self._elements == [] def push(self, element): self._elements.append(element) def pop(self): if self.is_empty(): raise ValueError element = self._elements.pop() return element def func(input_str): st = My_Stack() for ch in input_str: if ch == "[" or ch == "(": st.push(ch) elif ch == "]": if st.is_empty(): print("false") return element = st.pop() if element != "[": print("false") return elif ch == ")": if st.is_empty(): print("false") return element = st.pop() if element != "(": print("false") return else: continue if not st.is_empty(): print("false") else: print("true") input_str = input() func(input_str)