数据结构-顺序栈笔试题3
/*通过键盘输入一个包括不同类型括号的字符串string ,判断字符串是否有效。
*要求设计算法实现检查字符串是否有效,有效的字符串需满足以下条件:
- A.左括号必须使用相同类型的右括号闭合
- B.左括号必须以正确的顺序闭合
- C.每个括号都有一个对应的相同类型的左括号*/
设计思路:
1.遍历,遇到左括号则入栈
2.若遇到右括号,则判断类型,随之消除栈顶与之最近的同类型左括号
3.若栈空,则字符串有效
Str_JudgeIsValid_Total
/*通过键盘输入一个包括不同类型括号的字符串string ,判断字符串是否有效。
*要求设计算法实现检查字符串是否有效,有效的字符串需满足以下条件:
* A.左括号必须使用相同类型的右括号闭合
* B.左括号必须以正确的顺序闭合
* C.每个括号都有一个对应的相同类型的左括号*/
typedef struct {
int Top;
unsigned int Size;
Elemtype_t *Bottom;
} SeqStack_t;
bool SeqStack_IsEmpty(SeqStack_t *Manager) {
return (Manager->Top == -1);
}
bool SeqStack_IsFull(SeqStack_t *Manager) {
return (Manager->Top + 1 == Manager->Size);
}
bool Str_JudgeIsValid_Total(SeqStack_t *Manager){
char str[100];
printf("string = ");
scanf("%s", str);
int i = 0;
while (str[i] != '\0') {
// If it's a left bracket, push it onto the stack
if (str[i] == '(' || str[i] == '[' || str[i] == '{') {
if (SeqStack_IsFull(Manager)) {
printf("Stack overflow!\n");
return false;
}
Manager->Bottom[++Manager->Top] = str[i];
}
// If it's a right bracket, check top of stack for match
else if (str[i] == ')' || str[i] == ']' || str[i] == '}') {
if (SeqStack_IsEmpty(Manager)) {
// Trying to pop when nothing is there
return false;
}
char topChar = Manager->Bottom[Manager->Top];
if ((str[i] == ')' && topChar == '(') ||
(str[i] == ']' && topChar == '[') ||
(str[i] == '}' && topChar == '{')) {
Manager->Top--; // matched, pop
} else {
// mismatched bracket
return false;
}
}
i++;
}
// If the stack is empty, all brackets matched
return (Manager->Top == -1);
}

浙公网安备 33010602011771号