java栈实现括号匹枯物肆配,主要是使用栈队列算法,如下代码:
import java.util.Scannerimport java.util.Stack
/**
* @author Owner
*
*/
public class Main {
public static void main(String[] args) {
Scanner sc = new 蚂轿Scanner(System.in)
int n= sc.nextInt()//3条测试数据数据
Stack<Character> stack = null
while(n!=0){
//从控制台读入一个测试字符串[]() [(])
String str = sc.next()
//如果该输入字符串为奇数,说明不匹配
if(str.length() % 2 == 1){
System.out.println("No")
}else{
//说明字符是偶数
stack = new Stack<Character>()
//遍历第一条测试字符串[]() [(])
for(int i=0i<str.length()i++){
if(stack.isEmpty()){
//如果栈是空的
stack.push(str.charAt(i))
}else if(stack.peek() == '[' && str.charAt(i) == ']' || stack.peek() == '(' && 没轿str.charAt(i) == ')'){
//说明此时栈中字符不是空的,并且符合,
stack.pop()
}else{
stack.push(str.charAt(i))
}
}
if(stack.isEmpty()){
//如果栈是空的,说明括号匹配
System.out.println("Yes")
}else{
//说明栈不为空,括号不匹配
System.out.println("No")
}
}
n--
}
}
}
大概有这3个问题:
资源没有清理
部分逻辑错误
栈 *** 作错误
带注释修改如下:
#include<stdio.h>#include<stdlib.h>
#include<string.h>
struct Node
{
char fuhao
struct Node 敏卜兄*next
}
struct S
{
struct Node *top
struct Node *bottom
}
void start(struct S *s)
void clean(struct S *s)
void end(struct S **s)
char yulan(struct S *s)
void ruzhan(struct S *s, char a)
char chuzhan(struct S *s)
int panduan(struct S 桥袭*s)
int match(char a, char b)
int main()
{
int n, a, i
char arr[256], in, out
scanf("%d", &n)
fflush(stdin) // 清空输入缓存
struct S *s = (struct S *)malloc(sizeof(struct S))
start(s) // 创建第一个node(bottom),可以放在while外面
while (n>0)
{
int onlyr = 0 // 如果表达式消除后只剩右*符号,则弊清设为 1
gets(arr)
a = strlen(arr)
for (i = 0 i<a i++)
{
char fh = arr[i]
if (fh == '(' || fh == '[' || fh == '{')
{
in = fh
ruzhan(s, in)
}
else if (fh == ')' || fh == ']' || fh == '}')
{
out = yulan(s)
if (out == '\0')
onlyr = 1
if (!match(out, fh))
break
else
chuzhan(s)
}
}
if (panduan(s) && !onlyr)
printf("YES\n")
else
printf("NO\n")
clean(s)
n--
}
end(&s)
return 0
}
// 预览top,s->top在end之前都会有效
char yulan(struct S *s)
{
if (s->top)
return s->top->fuhao
return '\0'
}
int match(char a, char b)
{
return ((a == '(' && b == ')') ||
(a == '[' && b == ']') ||
(a == '{' && b == '}'))
}
// 这个栈在end之前始终有个node,bottom始终指向这个node
void start(struct S *s)
{
struct Node *p = (struct Node *)malloc(sizeof(struct Node))
p->fuhao = '\0'
p->next = 0
s->top = p
s->bottom = p
}
// 只保留bottom,清空其他node
void clean(struct S *s)
{
struct Node *p = s->top
while (p && p != s->bottom) {
struct Node *q = p->next
free(p)
p = q
}
//除了bottom其他都已经清除了,把top指针指向bottom
s->top = s->bottom
}
// 全部清除,包括 s栈 本身
void end(struct S **s)
{
clean(*s)
free((*s)->bottom)
free(*s)
*s = 0
}
void ruzhan(struct S *s, char a)
{
struct Node *p
p = (struct Node *)malloc(sizeof(struct Node))
p->next = s->top
p->fuhao = a
s->top = p
}
char chuzhan(struct S *s)
{
// 空栈直接返回'\0'
if (s->top == s->bottom) {
return '\0'
}
char c
struct Node *p
p = s->top
c = s->top->fuhao
s->top = s->top->next
free(p)
return c
}
int panduan(struct S *s)
{
return (s->top == s->bottom)
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)