題目
有效括號序列_牛客題霸_牛客網 (nowcoder.com)
Python
1長度必須為偶數
2就像開心消消樂一樣,一左一右就消掉。
class Solution:def isValid(self , s: str) -> bool:# write code here# flag=['()','{}','[]']# for _ in range(len(s)//2):# for i in flag:# if i in s:# s=s.replace(i,'')# # print(s)# if len(s)==0:# return True# else:# return Falseif len(s)%2==1:return Falsewhile '()' in s or '{}' in s or '[]' in s:s=s.replace('()','').replace('{}','').replace('[]','')return True if s=='' else False
C++
使用棧,遇到左括號,右括號進棧,遇到其他則取棧頂進行匹配
class Solution {
public:/*** 代碼中的類名、方法名、參數名已經指定,請勿修改,直接返回方法規定的值即可** * @param s string字符串 * @return bool布爾型*/bool isValid(string s) {// write code hereint n=s.size();if(n%2==1) return false;stack<char> sta;for(int _ =0;_<n;_++){if(s[_]=='(') sta.push(')');else if(s[_]=='{') sta.push('}');else if(s[_]=='[') sta.push(']');else{if(sta.empty()||sta.top()!=s[_])return false;sta.pop();}}return sta.empty();}
};
C語言
思路同c++
/*** 代碼中的類名、方法名、參數名已經指定,請勿修改,直接返回方法規定的值即可** * @param s string字符串 * @return bool布爾型*/
#include <string.h>
bool isValid(char* s )
{// write code hereint l=strlen(s);if(l%2==1) return 0;char *stack=(char* )malloc(l*sizeof(char));int top=0;for(int _ =0;_<l;_++){if(s[_]=='(') stack[top++]=')';else if(s[_]=='{') stack[top++]='}';else if(s[_]=='[') stack[top++]=']';else{if(top<1) return 0;if(stack[top-1]==s[_]) stack[--top]='\0'; //理解為c++處的pop};}if(strlen(stack)>0) return 0;return 1;
}