自学内容网 自学内容网

数据结构:有效的括号(OJ20)

给定一个只包括 '('')''{''}''['']' 的字符串 s ,判断字符串是否有效。

有效字符串需满足:

  1. 左括号必须用相同类型的右括号闭合。
  2. 左括号必须以正确的顺序闭合。
  3. 每个右括号都有一个对应的相同类型的左括号。

示例 1:

输入:s = "()"

输出:true

示例 2:

输入:s = "()[]{}"

输出:true

示例 3:

输入:s = "(]"

输出:false

示例 4:

输入:s = "([])"

输出:true

提示:

  • 1 <= s.length <= 104
  • s 仅由括号 '()[]{}' 组成
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <stdbool.h>

typedef char STDataType;
typedef struct Stack
{
STDataType* _a;
int _top;// 栈顶
int _capacity;  // 容量 
}Stack;

// 初始化栈 
void StackInit(Stack* ps)
{
assert(ps);
ps->_a = NULL;
ps->_capacity = ps->_top = 0;
}

// 入栈 
void StackPush(Stack* ps, STDataType data)
{
assert(ps);
if (ps->_capacity == ps->_top)
{
int newcapacity = ps->_capacity == 0 ? 4 : 2 * ps->_capacity;
STDataType* tmp = (STDataType*)realloc(ps->_a, newcapacity * sizeof(STDataType));
if (tmp == NULL)
{
perror("realloc fail!");
exit(1);
}
ps->_a = tmp;
ps->_capacity = newcapacity;
}
//空间足够
ps->_a[ps->_top++]=data;
}

// 检测栈是否为空,如果为空返回非零结果,如果不为空返回0 
bool StackEmpty(Stack* ps)
{
assert(ps);
return ps->_top==0;
}

// 出栈 
void StackPop(Stack* ps)
{
assert(ps);
assert(!StackEmpty(ps));
--ps->_top;
}

// 获取栈顶元素 
STDataType StackTop(Stack* ps)
{
assert(ps);
assert(!StackEmpty(ps));
return  ps->_a[ps->_top - 1];
}

// 获取栈中有效元素个数 
int StackSize(Stack* ps)
{
assert(ps);
return ps->_top;
}


// 销毁栈 
void StackDestroy(Stack* ps)
{
assert(ps);
if (ps->_a)
{
free(ps->_a);
}
ps->_a = NULL;
ps->_capacity = ps->_top = 0;
}

bool isValid(char* S)
{
Stack st;
StackInit(&st);
//遍历字符串
char* ps = S;
while (*ps != '\0')
{
if (*ps == '(' || *ps == '[' || *ps == '{')
{
StackPush(&st,*ps);
}
else
{
//右括号和栈顶元素比较
if (StackEmpty(&st))
{
return false;
}
//栈不为空才取栈顶元素比较
char ch = StackTop(&st);
if ((*ps == ')' && ch == '(')
|| (*ps == ']' && ch == '[')
|| (*ps == '}' && ch == '{'))
{
StackPop(&st);
}
else//不匹配
{
StackDestroy(&st);
return false;
}
}
ps++;
}
bool ret = StackEmpty(&st) == true;
//StackDestroy(&st);

return ret;
}

int main()
{
Stack ST;
//StackInit(&ST);
//StackPush(&ST, 1);
//StackPush(&ST, 2);
//StackPush(&ST, 3);
//isValid("(nihao}{}");
char input[] = "[]{}()";
bool result = isValid(input);
printf("%s has valid parentheses\n",input);
//while (!StackEmpty(&ST))
//{
//STDataType data = StackTop(&ST);
//printf("%s ", *&data);
////出栈
//StackPop(&ST);
//}
//StackDestroy(&ST);
return 0;
}


原文地址:https://blog.csdn.net/2303_81073778/article/details/142748044

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!