一.前言
如果想要使用C語言來解決這道題——有效的括號:https://leetcode.cn/problems/valid-parentheses/description/我們必須要借用上一篇我們所講的內容——棧的實現:https://blog.csdn.net/yiqingaa/article/details/138923750?spm=1001.2014.3001.5502
因為在C語言環境下,力扣不會主動幫你實現棧,需要用戶自己手動創建棧。但是在C++環境下,力扣會主動為我們實現棧。
2.正文?
1.1題目描述
1.2題目分析
1.21 題目想讓用戶干什么
這道題為我們用戶提供了一個字符串s。我們需要編寫程序來判斷所給字符串s中,相同類型的左括號與右括號是否一 一匹配。如果匹配正確就返回true。匹配不正確就返回false。
?1.22 如何求解題目
這道題我們可以運用棧的知識面來求出這道題。
我們可以先創建一個棧變量st,然后讓字符串s逐一遍歷字符,如果遍歷過程中字符是‘(’? ? ‘[’? ?‘{’? ?都可以將它們尾插到我們棧當中。如果在遍歷過程中不是‘(’? ? ‘[’? ?‘{’ ,而是‘)’? ? ‘]’? ?‘}’我們可以調用之前寫好的函數功能——取出棧頂元素( STDataType STTop(ST* ps) 這里的SLDataType是我們棧數據類型,可能是int、char或者其他類型。),調出可能之前存入棧的字符‘(’? ? ‘[’? ?‘{’ ,并與遍歷字符作對比。這里我暫且將取出棧頂的元素用變量top接受。我們就有取出棧頂元素,與現在遍歷字符的關系:
if ((top == '(' && *s != ')') ||
? ? ? ? ? ? (top == '{' && *s != '}') ||
? ? ? ? ? ? (top == '[' && *s != ']'))
滿足上面其中一個條件我們就可以說明,相同類型的左括號與右括號沒有一 一匹配。我們直接返回false即可。
值得注意的是:在返回true,或者false之前,都要對棧進行銷毀處理——void STDestroy(ST* ps)
1.3代碼實現
typedef int STDataType;
struct Stack
{STDataType* a;int top;int capacity;
};
typedef struct Stack ST;
void STInit(ST* ps);//棧的初始化
void STDestroy(ST* ps);//棧的銷毀void STPush(ST*PS,STDataType x);//入棧
void STPop(ST* ps);//出棧STDataType STTop(ST* ps);//取棧頂的數據bool STEmpty(ST*ps);//判空int STSize(ST* PS);//獲取數據個數
void STInit(ST *ps)//棧的初始化
{assert(ps);ps->a = NULL;ps->capacity = ps->top = 0;
}
void STDestroy(ST* ps)//棧的銷毀
{assert(ps);free(ps->a);ps->a = NULL;ps->top = ps->capacity = 0;
}
void STPush(ST* ps, STDataType x)//入棧
{assert(ps);if (ps->capacity == ps->top){int newcapacity = ps->capacity == 0 ? 10 : ps->capacity*2;STDataType* tmp = (STDataType*)realloc(ps->a, newcapacity * sizeof(STDataType));if (tmp == NULL){perror("realloc fail!");return;} ps->a = tmp;ps->capacity = newcapacity;}ps->a[ps->top] = x;ps->top++;
}
void STPop(ST* ps)//刪除棧頂元素
{assert(ps);assert(ps->a);ps->top--;
}
STDataType STTop(ST* ps)//取出棧頂元素
{assert(ps);assert(ps->top >= 0);return ps->a[ps->top-1];
}
bool STEmpty(ST* ps)//判斷棧內元素是否為空
{assert(ps);if (ps->top == 0)return true;return false;
}
int STSize(ST* ps)//獲取數據個數
{assert(ps);return ps->top ;
}
bool isValid(char* s)
{ST st;
STInit(&st);
while (*s)
{if (*s == '(' || *s == '{' || *s == '['){STPush(&st, *s);}else{if(STEmpty(&st))//這一步是必須的,因為如果棧為空且*s是')' ']' '}',說明
//題目給出的字符可能是這樣的“)”、“(){}]”。類似這種情況都是不符合題意的情況。return false;char top = STTop(&st);STPop(&st);//這里一定要進行尾部棧頂元素刪除,以便遍歷字符和棧內字符能夠對的上if ((top == '(' && *s != ')') ||(top == '{' && *s != '}') ||(top == '[' && *s != ']')){return false;}}++s;
}
if (st.top != 0)return false;
STDestroy(&st);
return true;
}
三.結言?
今天的題目分享就到此結束了,覺得對你有所幫助的同學,能不能求一個三連。