leetcode-有效的括号(三种语言不同思路)
生活随笔
收集整理的這篇文章主要介紹了
leetcode-有效的括号(三种语言不同思路)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
C語言?
bool isValid(char * s){int length = strlen(s);//因?yàn)樵O(shè)置的str空間是從下標(biāo)1開始的,所以要length/2+2//用length/2是因?yàn)槔ㄌ柖际桥鋵Φ?#xff0c;用一半的就行了char* str=(char*)malloc(length/2+2);memset(str,0,length/2+2);//初始化內(nèi)存空間int i,j=0;for(i=0;i<length;i++){if((*(s+i)=='(')||(*(s+i)=='{')||(*(s+i)=='[')){ j++;*(str+j)=*(s+i); }//'('與')'的ASCII值差1,'['與']','{'與'}'的ASCII值差2else if((*(s+i)==(*(str+j)+1))||(*(s+i)==(*(str+j)+2))){j--;}elsereturn false;}if(j)return false;return true; }C++ 利用棧進(jìn)行判斷
class Solution { public:bool isValid(string s) {stack<char>st;if(s.size()%2==1)return false; //奇數(shù)個(gè)括號,直接返回falsefor(int i=0;i<s.size();i++){switch(s[i]){case'(': //左括號入棧st.push(s[i]);break;case'[':st.push(s[i]);break;case'{':st.push(s[i]);break;case')': //遇到右括號,檢測棧頂if (st.empty()||st.top()!='(')return false;else{st.pop();break;}case']':if (st.empty()||st.top()!='[')return false;else{st.pop();break;}case'}':if (st.empty()||st.top()!='{')return false;else{st.pop();break;}}}return st.empty()?true:false;} };python
class Solution:def isValid(self, s: str) -> bool://如果括號是奇數(shù),肯定是錯(cuò)誤的if len(s)%2 != 0:return Falsewhile '()' in s or '[]' in s or '{}' in s:s = s.replace('[]','').replace('()','').replace('{}','')return True if s == '' else False?
總結(jié)
以上是生活随笔為你收集整理的leetcode-有效的括号(三种语言不同思路)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 笔记本 win7 装vs2010 报错
- 下一篇: leetcode-合并两个有序链表